一尘不染

SQL in(@Variable)查询

sql

我有以下代码,问题是我的变量列表@LocationList本质上是一个csv字符串。当我将其用作(@LocationList)中whereLocationID的一部分时,它说它不是int(LocationID是int)。我怎样才能使该csv字符串在子句中被接受?

Declare @LocationList varchar(1000)
Set @LocationList = '1,32'

select Locations from table where Where LocationID in (@LocationList)

阅读 205

收藏
2021-05-05

共1个答案

一尘不染

最有效的方法是使用动态SQL,例如提到rt2800(带有Michael Allen的注入警告)

但是,您可以创建一个函数:

ALTER  FUNCTION [dbo].[CSVStringsToTable_fn] ( @array VARCHAR(8000) )
RETURNS @Table TABLE ( value VARCHAR(100) )
AS 
    BEGIN
        DECLARE @separator_position INTEGER,
            @array_value VARCHAR(8000)

        SET @array = @array + ','

        WHILE PATINDEX('%,%', @array) <> 0 
            BEGIN
                SELECT  @separator_position = PATINDEX('%,%', @array)
                SELECT  @array_value = LEFT(@array, @separator_position - 1)

                INSERT  @Table
                VALUES  ( @array_value )

                SELECT  @array = STUFF(@array, 1, @separator_position, '')
            END
        RETURN
    END

并从中选择:

DECLARE @LocationList VARCHAR(1000)
SET @LocationList = '1,32'

SELECT  Locations 
FROM    table
WHERE   LocationID IN ( SELECT   *
                           FROM     dbo.CSVStringsToTable_fn(@LocationList) )

或者

SELECT  Locations
FROM    table loc
        INNER JOIN dbo.CSVStringsToTable_fn(@LocationList) list
            ON list.value = loc.LocationID

当您尝试从SSRS向PROC发送多值列表时,这非常有用。

2021-05-05