Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparison in SQL Server CASE clause

How would I go about the following query?

SELECT
CASE LEN(field1)
WHEN > 15    --Error: Incorrect syntax near '>'.
THEN SUBSTRING(field1, 1, 15)
ELSE field1
END
AS 'My Field'
FROM MyTbl

Can you not do comparisons like this in a CASE clause?

like image 376
Nick Rolando Avatar asked Aug 02 '26 16:08

Nick Rolando


1 Answers

SELECT
CASE 
WHEN LEN(field1) > 15
THEN SUBSTRING(field1, 1, 15)
ELSE field1
END
AS 'My Field'
FROM MyTbl

When you write it the way you had it, think of it like a switch statement, where you're making implicit equality comparisons. If you need more complex logic you need to write the CASE this way.

like image 160
Yuck Avatar answered Aug 04 '26 09:08

Yuck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!