tags:

views:

636

answers:

6

I have the following the query running dynamically

SELECT *
FROM Vehicles
WHERE (DKID IN (69954))
ORDER BY case when ImageName1 = 'na' then 0 else 1 end, Make , Model, Year DESC

This is returning the following error:

Error Executing Database Query. [Macromedia][SQLServer JDBC Driver][SQLServer]Incorrect syntax near 'na'.

Thanks in advanced for your help

A: 

Try enclosing the case statement in parentheses.

SELECT *
FROM Vehicles
WHERE (DKID IN (69954))
ORDER BY 
    (case when ImageName1 = 'na' then 0 else 1 end), Make , Model, Year DESC
Adam Robinson
+1  A: 

works for me

here is repo script

use tempdb
go

create table Vehicles(DKID int,ImageName1 varchar(50),
                          Make int, Model int, Year int)

insert Vehicles values (69954,'na',1,1,2007)
insert Vehicles values(69954,'bla',1,1,2008)
go

SELECT *
FROM Vehicles
WHERE (DKID IN (69954))
ORDER BY case when ImageName1 = 'na' then 0 else 1 end, 
Make , Model, Year DESC
SQLMenace
+4  A: 

are you running this query dynamically?, if so you might need to escape the quotes around 'na':

SELECT *
FROM Vehicles
WHERE (DKID IN (69954))
ORDER BY case when ImageName1 = ''na'' then 0 else 1 end, Make , Model, Year DESC
KM
I am running it dynamically, however the escape quotes still provide the same error.
Patcouch22
try replacing 'na' with char(110)+char(97), which will be slow, but will help diagnose it more...
KM
that did allow it to run...
Patcouch22
that shows that you are not escaping it properly, is "na" a constant or part of the dynamic query? edit your question to show that is generating the query, the propblem is there.
KM
A: 

Your query works fine for me in SQL Mgmt Studio... Maybe try it this way instead to see if it gets you anywhere:

SELECT
    case when ImageName1 = 'na' then 0 else 1 end as OrderCol,
    *
FROM Vehicles
WHERE (DKID IN (69954))
ORDER BY OrderCol,Make,Model,Year DESC
squillman
+1  A: 

You're using JDBC. Is there probably a transformation / interpretation from JDBC? Try making the 'na' a parameter. Check if there is a certain syntax in JDBC for string constants in queries. I don't use JDBC, so I could be completely wrong.

Stefan Steinegger
A: 

As KMike said, it looks like you didn't not escape properly.

Basically, when you ran your statement, it did not generate a syntactically correct SQL statement from the dynamic SQL.

Generally, when I am writing dynamic sql, I use a print statement to print the generated SQL. I can then review the generated sql visually for obvious mistakes, and then execute it it to make sure it works as expected.

If I made a mistake in the dynamic SQL, it will usually be revealed here.

Sean