Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLServer - Select bool if column begins with a string

I would like to select a boolean of whether or not a column begins with a certain string.

SELECT (name LIKE 'foo%') AS isFoo FROM bar;

Is there a way to do this without using an inline CASE?

like image 552
Jim Mitchener Avatar asked Mar 10 '11 19:03

Jim Mitchener


2 Answers

No

There is neither implicit boolean CAST in SQL Server nor a boolean type

SELECT CAST(CASE WHEN name LIKE 'foo%' THEN 1 ELSE 0 END AS bit) AS isFoo
FROM bar;
like image 84
gbn Avatar answered Sep 18 '22 18:09

gbn


You might not even need the cast depending on your usage:

SELECT CAST(PATINDEX('foo%'), name) AS bit) FROM bar

This will return 1 if the col starts with the text otherwise 0. No CASE involved.

like image 32
ktharsis Avatar answered Sep 19 '22 18:09

ktharsis