tags:

views:

129

answers:

2

I'm working with a legacy database with columns such as "item" and "desc" (for description).

Obviously, there's issues when trying to do an ordered select such as:

SELECT item, desc FROM blah ORDER BY desc

The intent is to do an ascending sort of column "desc", but SQL server gets confused since desc is also a modifier for order by... How do I escape the field name so that it work appropriately? Do I have to select a second copy of that column as a different name to use in the order by?

+14  A: 

Surround the keyword desc with square brackets:

SELECT item, [desc] FROM blah ORDER BY [desc]
Macros
This is true for all situations that require use of a reserved keyword as a literal.
Tomalak
A: 

select b.item,b.desc from blah as b order by b.desc asc

I was wrong. The above is indeed incorrect. Brackets are the way to go.

Eric
Why was this downvoted? Even if it's not the "best" answer, it does work...
GalacticCowboy
Considered that, but it would break legacy code (depending on retrieving "desc" later on, not "b.desc"). Might be workable if it's legal to select in a way as to get desc and b.desc both. Didn't pursue as it seemed ugly and unnecessary.
Brian Knoblauch
Brian, can you give an example when "it would break legacy code"?The best practice is to always qualify column names, and it never breaks code, it makes it more robust.http://sqlblog.com/blogs/alexander_kuznetsov/archive/2008/10/25/defensive-database-programming-qualifying-column-names.aspx
AlexKuznetsov
If I understand how it works, I'd have to find all the legacy references to lines like rs.getString("desc") and change them all to rs.getString("b.desc"). Normally not an issue, but this codebase passes ResultSets around all over the place and it gets ugly real quick trying to make even simple changes. Will need some heavy refactoring to make it reasonable again, but that's not happening for awhile (not our main project, just hopping in quick to make a tweak).
Brian Knoblauch
No--as long as b.desc is the only "desc" column, your RS calls in the outer code can still just call it "desc". rs.getString("desc") will still work.
RolandTumble
Brian, actually SELECT b.desc FROM ...is equivalent toSELECT b.desc AS [desc] FROM ...which means the the column's name in the result set is still desc.
AlexKuznetsov
Well it won't parse in either SQL Server 2000 or 2008 because desc is a reserved word and must have the brackets (or "). So it is a wrong answer.
HLGEM
Actually I am wrong. I've tested this on SQL 2000 and 2005 and this does not work at all. Brackets are needed.
Eric