SQL “if exists…” dynamic query

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

    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
    */
    

提交回复
热议问题