SQL - using a variable for an IN clause

后端 未结 7 1383
醉话见心
醉话见心 2021-01-21 09:50

I wish to do something like the following:

declare @FrameNumber nvarchar(20)
set @FrameNumber = \'(p1, p2)\'

select from myTable where c1 in @FrameNumber
         


        
7条回答
  •  一生所求
    2021-01-21 10:09

    I have another solution to do with split function,

    DECLARE @FrameNumber NVARCHAR(20)
    SET @FrameNumber = 'p1,p2'
    
    SELECT * FROM MyTable WHERE ProductCode IN 
    (SELECT Value FROM fn_Split(@FrameNumber, ','))
    

    OutPut:

    Split Functions:

    CREATE FUNCTION fn_Split (
        @String VARCHAR(8000)
        ,@Delimiter CHAR(1)
        )
    RETURNS @temptable TABLE (Value VARCHAR(8000))
    AS
    BEGIN
        DECLARE @idx INT
        DECLARE @slice VARCHAR(8000)
    
        SELECT @idx = 1
    
        IF len(@String) < 1
            OR @String IS NULL
            RETURN
    
        WHILE @idx != 0
        BEGIN
            SET @idx = charindex(@Delimiter, @String)
    
            IF @idx != 0
                SET @slice = left(@String, @idx - 1)
            ELSE
                SET @slice = @String
    
            IF (len(@slice) > 0)
                INSERT INTO @temptable (Value)
                VALUES (@slice)
    
            SET @String = right(@String, len(@String) - @idx)
    
            IF len(@String) = 0
                BREAK
        END
    
        RETURN
    END
    

提交回复
热议问题