I am trying to convert SQL code to Seqel to run it from my script. How do I convert this:
select code, count(1) as total
from school_districts
group by code order by total desc;
into Sequel? Or, is there a way to pass raw SQL to Sequel? Also the school_districts will be interpolated #{table_name}.
DB[:school_districts].select(:code).group_and_count(:code).reverse_order(:count)
is a Sequel way of executing that query. I did not however alias the count column, but I hope you can do with this.
Even though working in Sequel is preferable as it allows you to change DBMs without changing your code I would prefer you use the fetch method.
You can do it a couple ways:
Use []:
DB["your sql string"]
Use fetch:
DB.fetch("your sql string")
Related
I'd like to generate the following SQL with rails / arel:
SELECT * FROM GROUPS
WHERE id = 10
CONNECT BY PARENT_ID = ID
I don't want to use plain SQL except for the last statement which is oracle specific (the real query is much more complex and I don't want to perform endless string concatenations).
What I've tried so far:
Group.where(id: 10).join('CONNECT BY PARENT_ID=ID')
This does not work as it places the custom SQL before the WHERE statement (as it assumes it's a join).
So the actual question is, how to add a custom bit of SQL to a query after the WHERE statements?
My query that I put into a prepared statement is:
select *
from ( select seq, audit_ts, message_type
from log2
where 1 = 1
and message_type in ('SOURCE', 'DEST')
order by seq desc )
where ROWNUM <= ?
When I run the query in my application, I get:
java.sql.SQLSyntaxErrorException: ORA-00907: missing right parenthesis
EDIT: Here is the java executing the query. I am trying to return a set of search results, so the prefix contains the SELECT statement and then I can have any number of suffixes (in this excerpt "AUDIT_LOG_SEARCH2") which are the parameterized WHERE clauses based on the user search:
StringBuffer query = new StringBuffer(300);
query.append(dbAdapter.getQuery("AUDIT_LOG_ENTRY_PREFIX"));
query.append(dbAdapter.getQuery("AUDIT_LOG_SEARCH2"));
// Insert parameters to complete the sql prepared statement
PreparedStatement ps = _dbConn.prepareStatement(query.toString());
ResultSet rs = ps.executeQuery();
But the query runs fine when I run it separately in SQL Developer. The query was originally created for Postgres, then updated for Oracle. Any tips?
You need to set the variables into the preparedStatement before executing.
PreparedStatement ps = _dbConn.prepareStatement(query.toString());
ps.setInt(1, 10);
Please post what query.toString() gives you if that doesn't work. Not query, but query.toString()
What are you doing in your:
// Insert parameters to complete the sql prepared statement
Are you using correctly the methods ps.setString... or whatever? Or are you just replacing the question marks? the second might be corrupting your query.
Based on #AlexPoole and #EdGibbs comments, I decided to add a bunch more debug statements. It turns out the method was being recursively called with a different sql "suffix" later on in the program if certain conditions were met. The suffix was not updated with the necessary parenthesis for the new ROWNUM wrapping the statement. So although the ORA-00907 can be thrown for many different formatting problems, it was in fact a right parenthesis that was causing me problems :P
The prefix and suffix seems like a weird pattern in this code base for creating sql queries. I'm thinking of getting rid of this and refactoring so queries don't have to be built like that. Any advice??
So for anyone else who runs into this Oracle error, I would suggest logging the sql statement you are generating and play around with it in SQL Developer. If it works in there, but not in your application, your code is probably doing something funky :P
Im new with JDBC, and while executing some query i get a result that is inconsistent.
If i execute this query in sql developer (connected to a Oracle DB) i get 4 results
SELECT *
FROM someTable1 some1
JOIN someTable2 some2 on (some1.some_id= some2.other_id)
WHERE some2.some_date LIKE '01/01/01' OR some2.some_date IS NULL
Then, i load this same query from a properties file in java and execute the query and get 0 results... anyone know why this is happening? I first suspect of the single quotes in the propertie value but i dont know...
Thanks in advance and excuse my poor english! :)
The query doesn't contain any special characters which could confuse Java, the properties loader or JDBC, so you should get exactly the same results in SQL Developer and with JDBC.
In fact, SQL Developer is written in Java, so it is using JDBC to execute the queries.
Print the query to the console before you execute it to make 100% sure the code executes the query that you have in mind.
Next, you should check the type of some_date. LIKE is only defined for string types (VARCHAR and similar), not for date/time types.
Oracle has a set of helper functions to build queries for date/time types, for example:
some_date = to_date( '01/01/2001','mm/dd/yyyy')
or
TRUNC(some_date, 'DAY') = to_date( '01/01/2001','mm/dd/yyyy')
The second query strips hours, minutes, seconds, etc. from the column and will compare only days, months and years.
Note: Always use 4-digit years to avoid all kinds of odd problems.
<-------PeopleCode------>
Hi,
I have a SQL query that i have tried executing using both SQLEXEC and SQL.fetch() but the problem is, when I am passing the values to parameters (:1,:2...) it does not return a row but when I hardcode the values in the where clause of the query itself, it retrieves the correct value.
Can anybody help?
My query looks similar to the following sample query :
Select * from PS_rec1 where emplid=:1 and plan_type=:2
it returns no data till i hardcode the values.
I have checked the values at the back end and some data is there to be fetched. Moreover, the same query retrieves data when ran in TOAD.
Have you tried outputting your binds to a log file just before you use them in your SQL statement?
If the binds aren't working, but literals are, then perhaps your binds don't contain the values that you expect them to.
You could also try explicitly setting the binds to the values that you're expecting just before the SQL statement. This will prove that the way you're passing in the binds is working correctly.
It required another update to the same record to get the values fetched in SQL exec.
M not sure what was the problem but i guess it might be that the previous update did not write the changes to the db even after an explicit commit.
Ok, you need to put your exact SQLExec statement in the question.
But, do you really have "Select * ..." in a SQLExec? How many columns are in your table? Since you mention the where clause, is your statement
SQLExec("select * from PS_rec where emplid=:1 and plan_type=:2", &var1, &var2, &vartocontainthewholerow);
Which will work in a SQL tool (toad) but probably does not work in AE or any type of Peoplecode program.
Now if your table has three columns, should you not have something like this:
SQLExec("select emplid, plan_type, column3 from PS_rec where emplid = :1 and plan_type=:2", &emplidIn, &plan_typeIn, &emplidOut, &plan_typeOut, &column3Out);
Notice that with three columns in the table that emplid and plan_type are two of them, you need to list all the columns you want, not asterisks '*'. Kind of silly to select the emplid and plan_type though.
Given a table name and column name in a pair of variables, can I perform a select query without using dynamic sql?
for example, I'd like something nicer than this:
CREATE PROCEDURE spTest (#table NVARCHAR(30), #column NVARCHAR(30)) AS
DECLARE #sql NVARCHAR(2000)
SELECT #sql = N'SELECT ' + #column + N' FROM ' + #table
PRINT #sql
EXEC sp_executesql #sql
I'd like to do this because my dynamic sql version is 3x slower than the non-dynamic version (which doesn't support a programmable table/column name, hence this question).
The dynamic version is going to be 3x slower, solely because your'e going to be swapping in and out the table name, and the parser can't optimize for that.
You might want to use a nested switch statement of sorts in your routine and use that to select your SELECT statement from pre-defined tables/columns, especially if your schema won't be changed frequently. That should run lots faster, but you'll lose the true dynamic-ness.
So it sounds like the question is whether you can build and run a query at runtime without using dynamic SQL?
I'd say the answer is no. The choices are:
dynamic SQL - calling sp_ExecuteSQL or Exec() given a user-built string. Whether that's pass-through SQL using an ADO library and a Command object, or it's right within a sproc.
compiled SQL - using the usual objects (sprocs and UDF) with known good statements interacting with known good objects. Parsing is done beforehand in this case.