SQL:存储过程中的in子句:如何传递值 [英] SQL : in clause in stored procedure:how to pass values

查看:42
本文介绍了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)

查看详情此处.

马克

这篇关于SQL:存储过程中的in子句:如何传递值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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