Passing a SQL parameter to an IN() clause using typed datasets in .NET

后端 未结 8 1999
别跟我提以往
别跟我提以往 2020-11-28 10:31

First apologies as there are similar questions on this site, but none of them answer this problem directly.

Im using typed datasets in VS 2010. I create a TableAdapt

8条回答
  •  -上瘾入骨i
    2020-11-28 11:24

    You can't use a single parameter for a list of values in this way. But there may be database-specific ways to achieve what you want. For example, with SQL Server 2005 or later you could create a table-valued function to split your string parameter, something like:

    CREATE FUNCTION dbo.F_Split
    (
    @InputString VARCHAR(MAX)
    ,@Separator VARCHAR(MAX)
    )
    RETURNS @ValueTable TABLE (Value VARCHAR(MAX))
    AS
    BEGIN
    
        DECLARE @SeparatorIndex INT, @TotalLength INT, @StartIndex INT, @Value VARCHAR(MAX)
        SET @TotalLength=LEN(@InputString)
        SET @StartIndex = 1
    
        IF @Separator IS NULL RETURN
    
        WHILE @StartIndex <= @TotalLength
        BEGIN
            SET @SeparatorIndex = CHARINDEX(@Separator, @InputString, @StartIndex)
            IF @SeparatorIndex > 0
            BEGIN
                SET @Value = SUBSTRING(@InputString, @StartIndex, @SeparatorIndex-@StartIndex)
                SET @StartIndex = @SeparatorIndex + 1
            END
            ELSE
            BEGIN
                Set @Value = SUBSTRING(@InputString, @StartIndex, @TotalLength-@StartIndex+1)
                SET @StartIndex = @TotalLength+1
            END
            INSERT INTO @ValueTable
            (Value)
            VALUES
            (@Value)
        END
    
        RETURN
    END
    

    You would then use it as follows:

    SELECT * from Table WHERE ID IN (SELECT CAST(Value AS INT) FROM F_Split(@IDs, ','))
    

提交回复
热议问题