The following TQL query is generated from a tool I’m using but when it’s executed there is a syntax error near ‘LIKE’. I can’t seem to figure out what the problem is. Does anybody know what’s wrong?
The error from SQL Management Studio is “Msg 156, Level 15, State 1, Line 17 Incorrect syntax near the keyword ‘LIKE’.”
SELECT COUNT_BIG(*)
FROM [HistoryReport] AS t0
WHERE (1 <> 0 AND
(CASE WHEN (
(CASE WHEN (t0.[CategoryValue] IS NULL)
THEN NULL
ELSE LOWER(t0.[CategoryValue])
END) IS NULL
)
THEN NULL
ELSE (
(CASE WHEN (t0.[CategoryValue] IS NULL)
THEN NULL
ELSE LOWER(t0.[CategoryValue])
END) LIKE 'U' + '%'
)
END) <> 0)
A few things, It seems very strange that you are testing if a value is null, and returning null if it is and the value if it isn’t. Then you’re checking for nulls again in the branch of code that is only executed if the value is definitely not null. A bit unnecessary and very confusing. In addition, I suspect your comparison with
NULLisn’t going to work the way you think it is sinceNULL <> 0will evaluate toNULLby default.As an aside: normally, in SQL SERVER, strings are case-insensitive (unless you configure the column or server with a case-sensitive collation which is somewhat uncommon.)
I’m trying hard to figure out what you actually mean, here is a syntactically correct version of what I think you’re trying to do:
Basically your query states that if
t0.categoryValueisnull, returnnullotherwise convertt0.categoryvalueto lowercase and compare, usinglike, to ‘U%’ and return true if theLIKEcomparison returns true. The query above accomplishes the same thing.IF you aren’t using a case-sensitive collation, you can remove LOWER() since it only adds cost and prevents any index usage.
Now, in SQL Server’s world
NULLmeans ‘unknown’ so asking “Does this unknown value = 0” can only give the answer “I don’t know.” This confuses a lot of people because they expect “NULL==NULL” which works in some languages, but in SQL Sever you’re basically asking “Is this unknown value the same as this other unknown value” and the answer is, again, unknown.So I guess my only follow-up question, is how to do you want nulls to be treated?
Also, as to your original question, it would appear that expressions like your
LIKE 'U' + '%'don’t like being in the middle ofCASEstatements.BOL states the syntax is:
and that:
And what you have with
LIKEseems like it should be a valid expression but it appears thatLIKEis on the fringe of valid operatiors.