SQL “if exists…” dynamic query

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

    You can use EXEC to execute sql statement, then call @@ROWCOUNT which Returns the number of rows affected by the last statement, to check row exists in sql select stetement.

    DECLARE @Query VARCHAR(1000) = 'SELECT * FROM dbo.MyTable',@hasRow int
    EXEC (@Query)
    SELECT @hasRow =@@ROWCOUNT // Returns the number of rows affected by the last statement 
    PRINT @hasRow 
    
    IF @hasRow > 0
    BEGIN
        Print 1
    END
    BEGIN
        Print 2
    END
    

提交回复
热议问题