SQL “if exists…” dynamic query

后端 未结 5 1805
难免孤独
难免孤独 2021-01-04 01:19

Suppose I have a query stored in a variable like this (it\'s actually dynamically populated and more complex, but this is for demonstration purposes):

DECLAR         


        
5条回答
  •  星月不相逢
    2021-01-04 02:04

    I know this answer is too late. but, I'm leaving this here to help someone else to use IF EXISTS with a dynamic query.

    This is how you should do it with dynamic queries.

    DECLARE @Query VARCHAR(MAX)
    
    SET @Query = 'SELECT * FROM [dbo].[MyTable]'
    
    SET @Query = 'IF EXISTS (' + @Query + ')
                    BEGIN
                        -- do something
                        print ''1''
                    END
                ELSE
                    BEGIN
                       -- do something else
                       print ''0''
                    END
                '
    
    exec (@Query)
    

    Hope this helped someone. Vote if it did :)

提交回复
热议问题