duangelin7513 2013-01-30 22:53
浏览 58
已采纳

如何将PHP中作为参数的逗号分隔整数列表传递给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 [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.

The error I'm getting is:

Conversion failed when converting the varchar value '1,2,4,6,212' to data type int.

I've never done this before and research so far has yielded no positive results.

  • 写回答

2条回答 默认 最新

  • doumaoao0182 2013-01-31 05:54
    关注

    Firstly, let's use a SQL Function to perform the split of the delimited data:

    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, ','))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线