将列表传递到存储过程

时间:2014-10-27 19:50:31

标签: sql sql-server stored-procedures

我有两个需要插入数据库的ID列表。我想在这里做的是,将这两个列表传递给存储过程并尝试使用while循环添加它。我尝试使用用户定义的类型来定义数组,但不知道如何将它传递给插入命令

CREATE TYPE [dbo].[Array] AS TABLE(
[Item] [NVARCHAR](MAX) NULL
);

这是SQL / PL:

ALTER PROCEDURE [dbo].[sp_create_order]
(@productIds AS Array READONLY, @priceIds AS Array READONLY)
AS
BEGIN
  DECLARE @i int 
  DECLARE  @n int    


set @n = count(@productIds)
set @i = 1; 

while (@i <= @n) 
BEGIN    
INSERT INTO order_detail(product_id,price_id) 
    VALUES(@productIds[i],@priceIds[i]);
set @i = @i + 1; 
END 
END 
RETURN 0

2 个答案:

答案 0 :(得分:2)

考虑更改您的类型以包含两个对。

CREATE TYPE [dbo].[ProductPrices] AS TABLE(
[ProductId] [NVARCHAR](MAX) NULL,
[PriceId] [NVARCHAR](MAX) NULL
);

然后将您的程序更改为以下内容:

create procedure [dbo].[sp_create_order] @productPrices dbo.ProductPrices READONLY
as
begin
    insert into order_detail
    select p.ProductId,
        p.PriceId
    from @productPrices p
end

然后你可以这样调用你的程序。

declare @productPrices dbo.ProductPrices;

insert into @productPrices
values('1', '7'),
('2', '12'),
('3', '8');

exec dbo.sp_create_order @productPrices;

答案 1 :(得分:1)

看起来你正在学习表值参数,你应该用两列创建一个表值参数,这样就可以直接插入

这是解决当前问题的一种方法,我们可以使用ROW_NUMBER生成序列号,并从两个表中获取行值

create PROCEDURE [dbo].[sp_create_order]
(@productIds AS Array READONLY, @priceIds AS Array READONLY)
AS
BEGIN

INSERT INTO order_detail(product_id,price_id) 
select T1.item, T2.item
FROM
(select item , ROW_NUMBER() over ( order by (select null)) as seq from @productIds) T1
join
(select item , ROW_NUMBER() over ( order by (select null)) as seq from @priceIds) T2
on T1.seq = T2.seq


END