SQL “if exists…” dynamic query

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

    Try Executing the Dynamic query and use @@RowCount to find the existence of rows.

    DECLARE @Query  NVARCHAR(1000) = 'SELECT * FROM [dbo].[Mytable]',
            @rowcnt INT
    
    EXEC Sp_executesql @query
    
    SELECT @rowcnt = @@ROWCOUNT
    
    IF @rowcnt > 0
      BEGIN
          PRINT 'row present'
      END 
    

提交回复
热议问题