views:

4701

answers:

6

One of my columns is called "from". I can't change it, I didn't make it. Am I allowed to do something like "SELECT from FROM TableName"?

Or is there a special syntax to avoid the SQL server being confused?

I am using Microsoft SQL Server (express i think) and Java JDBC, if that matters...

Thanks

Nathan

+27  A: 

Wrap the column name in brackets like so, from becomes [from].

select [from] from table;
tvanfosson
+4  A: 

If you ARE using SQL Server, you can just simple wrap the square brackets around the column or table name.

select [select]
from [table]
John Baughman
+8  A: 

While you are doing it - alias it as something else (or better yet, use a view or an SP and deprecate the old direct access method).

SELECT [from] AS TransferFrom -- Or something else more suitable
FROM TableName
Cade Roux
A: 

Your question seems to be well answered here, but I just want to add one more comment to this subject.

Those designing the database should be well aware of the reserved keywords and avoid using them. If you discover someone using it, inform them about it (in a polite way). The keyword here is reserved word.

More information:

"Reserved keywords should not be used as object names. Databases upgraded from earlier versions of SQL Server may contain identifiers that include words not reserved in the earlier version, but that are reserved words for the current version of SQL Server. You can refer to the object by using delimited identifiers until the name can be changed." http://msdn.microsoft.com/en-us/library/ms176027.aspx

and

"If your database does contain names that match reserved keywords, you must use delimited identifiers when you refer to those objects. For more information, see Identifiers (DMX)." http://msdn.microsoft.com/en-us/library/ms132178.aspx

Eigir
+1  A: 

If it had been in PostgreSQL, use double quotes around the name, like:

select "from" from "table";

Note: Internally PostgreSQL automatically converts all unquoted commands and parameters to lower case. That have the effect that commands and identifiers aren't case sensitive. sEleCt * from tAblE; is interpreted as select * from table;. However, parameters inside double quotes are used as is, and therefore ARE case sensitive: select * from "table"; and select * from "Table"; gets the result from two different tables.

some
The double quotes work for MS SQL, too, without the case sensitivity, though. Quoted identifiers are just, AFAIK, an equivalent alternative to bracket-delimited identifiers.
P Daddy
A: 

Thanks for your suggestion.

Harish