stored proc - executing a query with NOT IN where clause

后端 未结 5 688
梦谈多话
梦谈多话 2021-01-26 09:58

i have a stored procedure

Create PROCEDURE abc      
  @sRemovePreviouslySelectedWhereClause nvarchar(max)
AS
BEGIN

SELECT * 
      FROM table 
     WHERE nId          


        
5条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-26 10:06

    First, create a split function which splits your delimited string into a table:

    CREATE FUNCTION [dbo].[Split]
    (   
     @String varchar(max)
    ,@Delimiter char
    )
    RETURNS @Results table
    (
     Ordinal int
    ,StringValue varchar(max)
    )
    as
    begin
    
        set @String = isnull(@String,'')
        set @Delimiter = isnull(@Delimiter,'')
    
        declare
         @TempString varchar(max) = @String
        ,@Ordinal int = 0
        ,@CharIndex int = 0
    
        set @CharIndex = charindex(@Delimiter, @TempString)
        while @CharIndex != 0 begin     
            set @Ordinal += 1       
            insert @Results values
            (
             @Ordinal
            ,substring(@TempString, 0, @CharIndex)
            )       
            set @TempString = substring(@TempString, @CharIndex + 1, len(@TempString) - @CharIndex)     
            set @CharIndex = charindex(@Delimiter, @TempString)
        end
    
        if @TempString != '' begin
            set @Ordinal += 1 
            insert @Results values
            (
             @Ordinal
            ,@TempString
            )
        end
    
        return
    end
    

    Then change your where clause as follows:

    select
     t.*
    from [yourTable] t
    where t.[ID] not in (select cast([StringValue] as int) from dbo.Split(@sRemovePreviouslySelectedWhereClause,','))
    

提交回复
热议问题