为一个 SQL 参数传递多个值 [英] Passing multiple values for one SQL parameter

查看:33
本文介绍了为一个 SQL 参数传递多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 CheckBoxList,用户可以在其中从列表中选择多个项目.然后我需要能够将这些值传递给我的存储过程,以便它们可以在 WHERE 条件中使用,例如:

I have a CheckBoxList where users can select multiple items from the list. I then need to be able to pass these values to my Stored Procedure so they can be used in a WHERE condition like:

WHERE ID IN (1,2,3)

我尝试这样做,因此它是一个 nvarchar 参数,我将字符串 1,2,3 传递给:

I tried doing this so that its a nvarchar parameter and i pass the string 1,2,3 with:

WHERE ID IN (@IDs)

但这返回了以下错误:

Conversion failed when converting the nvarchar value '1,2,3' to data type int

任何帮助将不胜感激!

推荐答案

有几种方法可以做到.您可以将参数作为 XML blob 传入,如下例所示:

There's a few ways of doing it. You could pass in the parameter as an XML blob like this example:

CREATE PROCEDURE [dbo].[uspGetCustomersXML]
    @CustomerIDs XML
AS
BEGIN
SELECT c.ID, c.Name
FROM [dbo].[Customer] c
JOIN @CustomerIDs.nodes('IDList/ID') AS x(Item) ON c.ID = Item.value('.', 'int' )
END
GO

--Example Use:
EXECUTE [dbo].[uspGetCustomersXML] '<IDList><ID>1</ID><ID>10</ID><ID>100</ID></IDList>'

或者将值作为 CSV 传递并使用拆分函数将值拆分为表变量(那里有很多拆分函数,快速搜索会抛出一个).

Or pass in the values as CSV and use a split function to split the values out into a table variable (there's a lot of split functions out there, quick search will throw one up).

CREATE PROCEDURE [dbo].[uspGetCustomersCSV]
    @CustomerIDs VARCHAR(8000)
AS
BEGIN
SELECT c.Id, c.Name
FROM [dbo].[Customer] c
JOIN dbo.fnSplit(@CustomerIDs, ',') t ON c.Id = t.item
END
GO

--Example Use:
EXECUTE [dbo].[uspGetCustomersCSV] '1,10,100'

如果您使用的是 SQL 2008 或更高版本,则可以使用表值参数,它允许您将 TABLE 变量作为参数传入.我博客关于这三个一段时间后,快速进行性能比较.

If you were using SQL 2008 or later, you could have used Table Valued Parameters which allow you to pass a TABLE variable in as a parameter. I blogged about these 3 approaches a while back, with a quick performance comparison.

这篇关于为一个 SQL 参数传递多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆