首先,将单个名称传递给存储过程时不需要引用它们。
using (SqlCommand cmd = new SqlCommand("MyStoredProc", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@longFilter", "Jack,Jill,Joe");
using (SqlDataReader reader = cmd.ExecuteReader())
{
...
}
}
然后,在存储过程中,您可以使用简单的文本函数和临时表,如下所示在逗号处拆分字符串,并为字符串的每个部分在临时表中添加一个条目:
DECLARE @temp AS TABLE (Name NVARCHAR(255))
IF ISNULL(@longFilter, '') <> ''
BEGIN
DECLARE @s NVARCHAR(max)
WHILE LEN(@longFilter) > 0
BEGIN
IF CHARINDEX(',', @longFilter) > 0
BEGIN
SET @s = LTRIM(RTRIM(SUBSTRING(@longFilter, 1, CHARINDEX(',', @longFilter) - 1)))
SET @longFilter = SUBSTRING(@longFilter, CHARINDEX(',', @longFilter) + 1, LEN(@longFilter))
END ELSE
BEGIN
SET @s = LTRIM(RTRIM(@longFilter))
SET @longFilter= ''
END
-- This was missing until 20140522
INSERT INTO @temp (Name) VALUES (@s)
END
END
稍后使用以下内容SELECT
获取名称在其中的所有人的列表,@temp
如果@temp
不包含任何行(未过滤的结果),则为所有人:
SELECT * FROM Personnel WHERE Name IN (SELECT Name FROM @temp) OR (SELECT COUNT(*) FROM @temp) = 0