HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

String comparison without CASE statements?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
casewithoutstatementscomparisonstring

Problem

Is there a shorter more terse way to do a string comparison in SQL Server without wrapping it in a CASE WHEN ... THEN 1 END? In PostgreSQL, I can do

SELECT c, c='foo'
FROM ( VALUES ('foo'),('bar') ) AS t(c);


In SQL Server, I have to do

SELECT c, CASE WHEN c='foo' THEN 1 END
FROM ( VALUES ('foo'),('bar') ) AS t(c);


In the abstract, is there an easier more SQL-Servery way to throw an expression into boolean context? Or, is there a better way to write strcmp without rolling your own case statement?

Solution

I'm not sure that you'd call it shorter, but you could use the Logical Function IIF. From the docs,


IIF is a shorthand way for writing a CASE expression. It evaluates the Boolean expression passed as the first argument, and then returns either of the other two arguments based on the result of the evaluation.

Per the example,

SELECT c, iif(c='foo',1,0)
FROM ( VALUES ('foo'),('bar') ) AS t(c);

Code Snippets

SELECT c, iif(c='foo',1,0)
FROM ( VALUES ('foo'),('bar') ) AS t(c);

Context

StackExchange Database Administrators Q#212811, answer score: 3

Revisions (0)

No revisions yet.