如何在查询中编写包含多个参数的存储过程?

时间:2012-03-17 06:08:18

标签: sql sql-server sql-server-2008 sql-server-2005 tsql

我想写一个像这样的存储过程

Create Proc dbo.GetApplicantsByIDs

as

Select * from Applicants where ID in (1,2,3,4)

我如何将1,2,3作为参数传递,这些ID可能是多个。

3 个答案:

答案 0 :(得分:6)

您可以将您的ID作为XML发送给SP。

create procedure dbo.GetApplicantsByIDs
  @IDList xml
as

-- Table to hold the id's
declare @IDs table(ID int primary key)

-- Fill table with id's  
insert into @IDs(ID)
select X.ID.value('.', 'int')
from @IDList.nodes('/i') as X(ID)

select * 
from Applicants 
where ID in (select ID 
             from @IDs)

参数字符串应如下所示:

'<i>1</i><i>2</i><i>3</i>'

答案 1 :(得分:1)

我认为有更好的解决方案。 您可以创建如下函数:

CREATE FUNCTION [dbo].[Split] (@sep char(1), @s varchar(8000))
RETURNS table
AS
RETURN (
    WITH Pieces(pn, start, [stop]) AS (
      SELECT 1, 1, CHARINDEX(@sep, @s)
      UNION ALL
      SELECT pn + 1, [stop] + 1, CHARINDEX(@sep, @s, [stop] + 1)
      FROM Pieces
      WHERE [stop] > 0
    )
    SELECT pn as [index],
      SUBSTRING(@s, start, CASE WHEN [stop] > 0 THEN [stop]-start ELSE 8000 END) AS value
    FROM Pieces
  )

然后,您可以从输入数据'20,10,15,18,19'

中获取结果
SELECT * FROM [dbo].[Split](',', '20,10,15,18,19')

结果将是:

index   value
1   20
2   10
3   15
4   18
5   19

我可以重写你的程序如下:

Create Proc dbo.GetApplicantsByIDs         
         @Ids NVARCHAR(MAX)
as         

Select * from Applicants where ID in 
(SELECT value FROM [dbo].[Split](',', @Ids)

答案 2 :(得分:1)

使用表变量的另一种解决方案(为此):

if exists (select table_name from information_schema.tables where table_name = 'Applicants')
    drop table Applicants
go

create table Applicants (
    Id int identity,
    Name varchar(50)
)
go

insert Applicants (Name) values ('David')
insert Applicants (Name) values ('John')
insert Applicants (Name) values ('Scott')
insert Applicants (Name) values ('Anna')
insert Applicants (Name) values ('Esther')
go

create type IDs as table (
    ID int
)
go

if exists (select routine_name from information_schema.routines where routine_name = 'GetApplicantsByIDs')
    drop proc GetApplicantsByIDs
go

create proc GetApplicantsByIDs (
    @IDs IDs readonly
)
as 
begin
    select * from Applicants A where Id in (select * from @IDs)
end
go


declare @MyIDs as IDs
insert @MyIDs values (2)
insert @MyIDs values (4)
insert @MyIDs values (1)

exec GetApplicantsByIDs @MyIDs
go

产地: 1大卫 2约翰 4安娜