SQL “if exists…” dynamic query

不羁岁月 提交于 2019-11-30 17:59:25

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 

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

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 :)

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

Hi I think that only way is to put IF EXISTS part into code of execution. My case is to stop execution in point when select affects at least one row, that is goal of IF EXISTS.

Little example that saves reading all records covering by condition to first occurence:

set nocount off;
drop table if exists #temp
go
create table #temp (idCol int identity(1,1),someText nvarchar(1))
go
insert into #temp values ('a')
go 25000

declare @query nvarchar(max)
,@resultFork bit
set @query = 'if exists (select * from #temp where idCol % 3 = 0)
    set @resultFork=1
    else
    set @resultFork=0'
print @query
exec sp_executeSQL @query, N'@resultFork int output', @resultFork=@resultFork output
print @resultFork
/*Now U can use @resultFork in simple if condition...
if @resultFork = 1 
begin
    --
end
else 
begin
    --
end
*/
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!