SQL “if exists…” dynamic query

后端 未结 5 1784
难免孤独
难免孤独 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:15

    Try this:

    DECLARE @Query NVARCHAR(1000) = 'SELECT @C = COUNT(*) FROM dbo.MyTable'
    DECLARE @Count AS INT
    EXEC sp_executesql @Query, N'@C INT OUTPUT', @C=@Count OUTPUT
    
    IF (@Count > 0)
    BEGIN
    
    END
    

提交回复
热议问题