Can ObjectQuery.OrderBy() use NEWID()? - sql

I found that Entity SQL support NEWID(), but does ObjectQuery support it as well?
http://msdn.microsoft.com/en-us/library/bb738616.aspx,
Can I write objectquery like:
context.member.orderby("NEWID()").select("it.UserID");
or something like this? or I should write in other way?
I thought if entity sql support NEWID() function, it should be accepted by ObjectQuery also. Like you can use distinct(it.UserID), or BitWiseAND(it.UserID, 1) in ObjectQuery.Where() or Select().
Many thanks.

This is a SQL Server-specific canonical function, so it should be prefixed with 'SqlServer':
context.member.orderby("SqlServer.NEWID()").select("it.UserID");
Unfortunately, this will not work either: the Where extension method needs at least one reference to the immediate input scope.

Thanks Devart for response.
Actually, I found that I can use like:
var query1 = context.member.select("it.userid, SqlServer.NEWID() as newid").orderby("it.newid");
this can make random order for result, you will find that NEWID() is in the translated sql query.
but if you want to select partially result from 'query1' result set, you cannot write:
var query2 = context.member.select("it.userid, SqlServer.NEWID() as newid").orderby("it.newid").select("it.userid");
because when you use sql profiler to watch the sql that translated pass into sql server, you will find that the 'NEWID()' disappear.
However, I think 'query2' should be make sense. But it doesn't work.

Related

How to express this with jOOQ "Select alias.*, otherAlias.Column From .."

I am trying to use jOOQ to dynamically construct queries. So far it is going really well, but now I stumbled upon a case that I can not seem to express.
This is a simplified version of the query I want to generate:
Select alias.*, otherAlias.aColumn as aAlias
From table as alias
inner join otherTable as otherAlias
on alias.someColumn = otherAlias.someOtherColumn
Where otherAlias.someOtherColumn in (????????)
My problem is that i cannot seem to express the SELECT part how I need it. If I just use:
.select() -> I get select *
.select(alias.fields()) -> I get Select *
.select((alias.fields() :+ field(name(otherAlias, aColumn)).as(aAlias)):_*) -> I get Select otherAlias.aColumn as aAlias
Is there a way to express this with jOOQ?
The rest of the statement seems to work as expected. I am using jOOQ 3.10.7 in Scala and targeting Postgres at the moment and my statement currently looks like this:
sql
.select()
.from(alias)
.innerJoin(otherAlias)
.on(field(name(alias, someColumn)).eq(field(name(otherAlias, someOtherColumn))))
.where(condition)
Thanks a lot.
Update: I found a way to express this that seems to work by falling back to plain SQL. But I am still wondering whether there is a better way to express this. This works as a select:
.select((field(""""Alias".*"""), field(name(otherAlias, aColumn)).as(aAlias)):_*) -> I get Select "Alias".*, otherAlias.aColumn as aAlias
Assuming that you're using jOOQ 3.11 (which added support for unqualified asterisks and qualified asterisks), you can just write
alias.asterisk()
Or even, using jOOQ's scala extensions
alias.*
This is especially powerful when using the code generator.

Expression Builder to SQL Query

I know, that similiar post was posted already (SQL query from Toplink expression), but I didnt find an answer there. I would like to get SQL query from Expression Builder expression:
I have
Expression exp = builder.get(NUMBER.getAttributeName()).equal(getNumber());
and I want to see the SELECT statement, like (Select * from table WHERE number=....)
Or is it possible to execute the expression from Expression Builder without session? (I know that when I used query.prepareCall(session, new DatabaseRow()) I can obtain statement, but I just need to avoid using session. Thank you very much.
You must have the Session (what are you going to execute it on without a Session???).
query.prepareCall(session, new DatabaseRow())
This is how you get the SQL, you need to create a ReadAllQuery with the expression to be able to get the SQL (an Expression is just a where clause).
The problem was, that i wasnt able to create session because I couldnt register my project. And that was because I miss one line of code in my Project.class
setName(APPLICATION_NAME);
After this, I was able to create session and execute query. Thank you anyway

Dynamically building WHERE clauses in SQL statements

I have a question regarding SQL. I have the following SQL statement:
SELECT id, First, Last, E_Mail, Notes
FROM mytable
WHERE SOMETHING_SHOULD_BE_HERE IS NOT NULL;
I know that the SOMETHING_SHOULD_BE_HERE should be a column(attribute) in my table. Is their a way I can put a variable that can refer to the column I'm trying to access? In my case their are 30 columns. Can I have a string for SOMETHING_SHOULD_BE_HERE that can be assigned in my program to the column in which I want to search?
Thanks
No. Variables in SQL can refer to data, but not to object names (columns, functions or other database objects).
If you are building the SQL query, you'll need to use string operations to build your query.
The column can't be variable, but the value of the column can. The parser needs to know what to bind to.
If you elaborate on what you're trying to solve and which platform you're using it would allow for more complete answers.
You can have different SQLs queries in your code and use each one according to the case.
Another way is generate dynamically the query according the fields you want.
Without dynamic SQL, this is probably your best bet:
SELECT
id, first, last, email, notes
FROM
My_Table
WHERE
CASE #column_name_variable
WHEN 'column_1' THEN column_1
WHEN 'column_2' THEN column_2
...
ELSE 'not null'
END IS NOT NULL
There might be some issues with data type conversions, so you might need to explicitly cast all of the columns to one data type (VARCHAR is probably the best bet). Also, there's a good chance that performance will be horrendous on this query. I'd test it thoroughly before even thinking about implementing something like this.
I mentioned this in my comment, but for completeness I'll put it here too... you can probably also accomplish this with dynamic SQL, but how you do that will depend on your database server (MS SQL Server, Oracle, mySQL, etc.) and there are usually some caveats to using dynamic SQL.
In JDBC program, yes,the select statement can be composed like string operation.
for(String colName: colList)
{
String sql="Select id, First, Last, E_Mail, Notes From mytable where "+colName+" IS NOT NULL";
//execute the sql statement
}
It depends on how you are going to find out the value of SOMETHING_SHOULD_BE_HERE.
If you are in an Oracle PLS/SQL environment you could build up the WHERE clause using dynamic SQL and then use EXECUTE IMMEDIATE to execute it.
If you have a small set number of possibilities you could use CASE to workaround your problem possibly.
Your question is unclear.
However I am quite sure that what you have in mind is the so-called dynamic SQL (and related). "Dynamic SQL" allows you to dynamically build and submit queries at runtime. However such functionalities may not exist for your RDBMS.
There are several ways to do this.
When your query would return one and only one row
then you have to consider the EXECUTE IMMEDIATE statements (along with sp_executesql in tSQL : http://msdn.microsoft.com/en-us/library/ms188001.aspx ; or the USING clause in PL/SQL : http://docs.oracle.com/cd/B14117_01/appdev.101/b10807/13_elems017.htm to specify a list of input/output bind arguments) and/or PREPARED statements (http://rpbouman.blogspot.fr/2005/11/mysql-5-prepared-statement-syntax-and.html).
When your query can return more than one row
then you have to consider techniques such as the EXECUTE IMMEDIATE statement with the BULK COLLECT INTO clause or the OPEN-FOR, FETCH, and CLOSE statements (explicit cursors in PL/SQL :
http://docs.oracle.com/cd/B28359_01/appdev.111/b28370/dynamic.htm)
Please note that except in some particular cases, most conventional techniques like IF-THEN-ELSE and CASE statements should be preferred (along with a good algorithm). Furthermore they work with almost all RDBMS.

Encoding string in order to Insert SQLite

I'm using sqlite3_exec() function in order to execute an SQL Insert command. The problem starts when I need to insert strings that need to be encoded.
For example, I want to insert the following string: "f('hello')". If I want to insert this string I need to change "'" to "''".
My question is, how do I encode these strings? Is there a function I can count on? or a table that details all the needed encodes?
Thanks! :-)
Instead of manually escaping strings (which is error-prone and invites SQL injection attacks), I'd strongly recommend using prepared statements and bind values; read up on sqlite3_bind_XXX and sqlite3_prepare_v2
Using bind values will solve this problem and it will also make sqlite faster because it remembers previously executed sql statements and it can reuse their execution plans. This doesn't work when the sql statement is always slightly different because it hashes the complete sql statement.
sqlite_mprintf supports %q for that.
"Maybe" you should use something like a prepared statement. I am not an expert in SQLite, but I found this link (http://www.sqlite.org/c3ref/stmt.html) and it could help you. It is about SQL Statement Object.

SQL Command ISNULL for ODBC Connection

I'm connected to an OpenEdge DataServer via ODBC (not our product, we are just accessing their database, I hardly have any information and certainly no help from the other side).
Anyhow, I just need to execute a simple Select, add a couple of rows and I need the equivalent of an IsNull statement.
Basically I'd like to execute
SELECT ISNULL(NULL,'test')
This fails with a Syntax Error. I've looked around at something they misleadingly call a "documentation" but there are only references to SP_SQL_ISNULL but I can't get that to work either. I'm fit in T-SQL, so any pointers in any direction appreciated, even if it's just a RTFM with a link to TFM :)
Thanks
Thanks to Catalin and this question I got on the right track. I kept thinking I needed a OpenEdge specific function but actually I needed to use only ODBC SQL syntax.
To get what
ISNULL(col,4)
does you can use
COALESCE(col,4)
which "returns the data type of expression with the highest data type precedence. If all expressions are nonnullable, the result is typed as nonnullable."MSDN
Basically it will convert to 4 if the value is null (and therefore not convertable).
I am not 100% sure, but I think ODBC driver expects a valid SQL statement, and not an DBMS specific SQL statement, like the one you provided.