简体   繁体   English

如何将PHP中作为参数的逗号分隔整数列表传递给SQL Server 2008中的存储过程?

[英]How can I pass a comma-separated list of integers from PHP as a parameter to a stored procedure in SQL Server 2008?

Hopefully I'm going about this the right way, if not I'm more than open to learning how this could be done better. 希望我能以正确的方式解决这个问题,如果不是的话,我更愿意学习如何做得更好。

I need to pass a comma separated list of integers (always positive integers, no decimals) to a stored procedure. 我需要将一个逗号分隔的整数列表(总是正整数,没有小数)传递给存储过程。 The stored procedure would then use the integers in an IN operator of the WHERE clause: 然后,存储过程将使用WHERE子句的IN运算符中的整数:

WHERE [PrimaryKey] IN (1,2,4,6,212);

The front-end is PHP and connection is made via ODBC, I've tried wrapping the parameter in single quotes and filtering them out in the stored procedure before the list gets to the query but that doesn't seem to work. 前端是PHP并且通过ODBC建立连接,我尝试将参数包装在单引号中,并在列表到达查询之前在存储过程中将其过滤掉,但这似乎不起作用。

The error I'm getting is: 我得到的错误是:

Conversion failed when converting the varchar value '1,2,4,6,212' to data type int. 将varchar值'1,2,4,6,212'转换为数据类型int时转换失败。

I've never done this before and research so far has yielded no positive results. 我以前从未这样做过,迄今为止的研究没有取得任何积极成果。

Firstly, let's use a SQL Function to perform the split of the delimited data: 首先,让我们使用SQL函数来执行分隔数据的拆分:

CREATE FUNCTION dbo.Split
(
    @RowData nvarchar(2000),
    @SplitOn nvarchar(5)
)  
RETURNS @RtnValue table 
(
    Id int identity(1,1),
    Data nvarchar(100)
) 
AS  
BEGIN 
    Declare @Cnt int
    Set @Cnt = 1

    While (Charindex(@SplitOn,@RowData)>0)
    Begin
        Insert Into @RtnValue (data)
        Select 
            Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))

        Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
        Set @Cnt = @Cnt + 1
    End

    Insert Into @RtnValue (data)
    Select Data = ltrim(rtrim(@RowData))

    Return
END

To use this, you would simply pass the function the delimited string as well as the delimiter, like this: 要使用它,您只需将函数传递给分隔字符串以及分隔符,如下所示:

SELECT
  *
FROM
  TableName
WHERE
  ColumnName IN (SELECT Data FROM dbo.Split(@DelimitedData, ','))

If you still have issues, due to the datatype, try: 如果由于数据类型仍有问题,请尝试:

SELECT
  *
FROM
  TableName
WHERE
  ColumnName IN (SELECT CONVERT(int,Data) FROM dbo.Split(@DelimitedData, ','))

You can pass a comma separate list of values. 您可以传递逗号单独的值列表。 However, you cannot use them as you like in an in statement. 但是,您不能在in语句中使用它们。 You can do something like this instead: 你可以这样做:

where ','+@List+',' like '%,'+PrimaryKey+',%' 

That is, you like to see if the value is present. 也就是说,您希望查看该值是否存在。 I'm using SQL Server syntax for concatenation because the question is tagged Microsoft. 我正在使用SQL Server语法进行连接,因为问题标记为Microsoft。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM