SQL:存储过程中的in子句:如何传递值
我想编写一个 SQL Server 2005 存储过程,它将从用户表中选择并返回用户记录,以获取作为参数传递给存储过程的某些用户 ID.
I want to write a SQL Server 2005 stored procedure which will select and return the user records from the user table for some userids which are passed to the stored procedure as parameter.
如何做到这一点?
我可以将用户 ID 作为以逗号分隔的字符串传递.这样我就可以使用
I can pass the user ids as a string separated by comma. So that I can use the
select *
from users
where userid in (userids)
例如: 我想为 id 的 5,6,7,8,9 选择记录
E.g. : I want to select records for id's 5,6,7,8,9
如何编写存储过程?
对于 SQL Server 2005,请查看 Erland Sommarskog 出色的 SQL Server 2005 中的数组和列表 文章,展示了如何在 SQL Server 2005 中处理列表和数组的一些技术(他还有另一篇关于 SQL Server 2000 的文章).
For SQL Server 2005, check out Erland Sommarskog's excellent Arrays and Lists in SQL Server 2005 article which shows some techniques how to deal with lists and arrays in SQL Server 2005 (he also has another article for SQL Server 2000).
如果您可以升级到 SQL Server 2008,您可以使用名为表值参数"的新功能:
If you could upgrade to SQL Server 2008, you can use the new feature called "table valued parameter":
首先创建一个用户自定义的表类型
First, create a user-defined table type
CREATE TYPE dbo.MyUserIDs AS TABLE (UserID INT NOT NULL)
其次,在您的存储过程中使用该表类型作为参数:
Secondly, use that table type in your stored procedure as a parameter:
CREATE PROC proc_GetUsers @UserIDTable MyUserIDs READONLY
AS
SELECT * FROM dbo.Users
WHERE userid IN (SELECT UserID FROM @UserIDTable)
查看详情此处.
马克