SQL Server Flag if a string is present in a select

jjhzyzn0  于 2023-04-19  发布在  其他
关注(0)|答案(1)|浏览(125)

I need to check if there is a specific sequence of characters in a select and if so, indicate the case by setting a variable.

This is what I tried:

SELECT 
    @FLAG = CASE 
                WHEN '%ABC%' IN (SELECT [COLUMN] 
                                 FROM [TABLE] 
                                 WHERE [CONDITION]) 
                    THEN 1 
                    ELSE 0

but it doesn't work because the @FLAG result is always "0"

(the output of the SELECT is a list of rows)

kiz8lqtg

kiz8lqtg1#

You should change your criteria to use EXISTS , like

SELECT 
    @FLAG = CASE 
                WHEN EXISTS (SELECT [COLUMN] 
                             FROM [TABLE] 
                             WHERE [CONDITION] AND [COLUMN] LIKE '%ABC%') 
                    THEN 1 
                    ELSE 0

unless you are interested to find records where [COLUMN] is exactly '%ABC%'

相关问题