且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将 s-s-rS 中的多个值参数传递给存储过程

更新时间:2023-11-26 17:02:52

对了,我需要先给你一些背景知识.

Right I need to give you some back ground 1st.

当您允许 s-s-rS 参数选择多个值时,选择多个值会创建一个逗号分隔的值字符串作为一个字符串

When you allow s-s-rS parameter to select multiple values, The selection of multiple values creates a comma deliminated string of value as one string

  'value1,value2,value3'

要使用 IN 运算符检查字符串中的值,我们需要用逗号连接的字符串,例如....

To check values in a string using IN operator we need strings concatenated with commas something like this ....

  'value1','value2','value3'

你的程序

现在在您的 proc 中,当您显式插入值时,它会将多个值插入到您的表中.

Now in your proc when you insert values explicitly it inserts multiple values into your table.

  INSERT INTO Table_Value_Param
  VALUES ('value1'),       --<-- 1st value/Row
         ('value2'),       --<-- 2nd Value/Row
         ('value3')        --<-- 3rd Value/Row

当你在你的过程中执行像

and this gives you back the expected results as when inside your procedure you execute a statement like

SELECT * 
FROM Table_Name
WHERE ColumnName IN (SELECT ColumnName 
                     FROM Table_Value_Param)

另一方面,当您尝试使用 s-s-rS 报告参数插入表格时,您的表格会插入类似

On the other hand when you try to insert into table using s-s-rS report Parameter you table inserts value like

  INSERT INTO Table_Value_Param
  VALUES ('value1,value2,value3')   --<-- One Row/Value containing all the values comma separated

解决方案

在这种情况下创建 TVP 并没有真正的帮助,我所做的是在我的程序中使用 dbo.Split() 函数.

Creating TVP in this situation doesnt really help, What I do is make use of dbo.Split() function inside my procedure.

你可以在网上找到很多关于 split 函数的定义,一些很酷的可以看这里 tsql 中等价的拆分函数?

You can find many definitions for split function online, for a some cool ones have a look here Split Function equivalent in tsql?

一旦你创建了这个拆分函数,只需在你的过程定义中使用这个函数,你甚至不需要表值参数.

Once you have created this split function just use this function inside your procedure definition you dont even need the Table valued parameters then.

这样的东西...

  SELECT * 
  FROM Table_Name 
  WHERE ColumnName IN ( 
                       SELECT Value
                       FROM dbo.Split(@Report_Param, ',')
                       )