我想编写一个存储过程,可以接收一个或多个员工ID并根据这些ID返回数据。每次调用sproc时,员工ID的数量都会有所不同。
如何编写存储过程以返回传入的每个员工ID的分支地址,其中员工ID的数量是可变的?
答案 0 :(得分:1)
如果您运行的是SQL 2008或更高版本,那么我建议您使用表格类型。然后,您可以将表传递给存储过程。这是我为证明这一点而做的一个小例子。
create database tmpDB;
go
use tmpDB;
go
create table tblEmployee
(
ID int identity(1, 1)
primary key
not null,
Name nvarchar(200),
Branch_ID int
);
go
insert into dbo.tblEmployee
(Name, Branch_ID)
values (N'Brian', 1),
(N'Mary', 1),
(N'Peter', 2),
(N'Sonya', 2),
(N'Roland', 1),
(N'Tom', 3),
(N'Sam', 3),
(N'Ryan', 3),
(N'Julia', 3),
(N'Tim', 1),
(N'Eva', 2);
go
select *
from dbo.tblEmployee;
go
create type typEmployee as table
(
Name nvarchar(200),
BranchID int
);
go
grant exec on type::typEmployee to public;
go
create procedure spInsertEmployees
(
@NewEmployees typEmployee readonly
)
as
begin
merge tblEmployee as target
using
(
select Name,
BranchID
from @NewEmployees
) as source (Name, BranchID)
on (
target.Name = source.Name
and target.Branch_ID = source.BranchID
)
when not matched then
insert (Name, Branch_ID)
values (
source.Name,
source.BranchID
);
end;
go
grant execute on spInsertEmployees to public;
go
declare @tmpTable typEmployee;
insert into @tmpTable
(Name, BranchID)
values (N'NewEmployee', 1),
(N'NewEmployee', 2),
(N'NewEmployee', 3),
(N'Sonya', 2),
(N'Tim', 1);
exec dbo.spInsertEmployees
@NewEmployees = @tmpTable;
select *
from dbo.tblEmployee;
go
use master;
go
drop database tmpDB;
go
答案 1 :(得分:0)
我们所做的只是传递一个分隔列表。所以1,2,3,42,55,6666具有nvarchar(max)。
然后我们有一个用户定义的函数返回一个表,我们就加入了它。
Google使用分隔符搜索t sql split string,您将找到示例。
从dbo.udfSplit中选择*(@inputfromparameters,",")内部联接....