简体   繁体   English

将列表传递到存储过程

[英]Passing a list into a stored procedure

I have two lists of IDs that needs to be inserted into the database. 我有两个需要插入数据库的ID列表。 What I am want to do here is, passing these two lists into a stored procedure and trying to add it with a while loop. 我要在这里做的是,将这两个列表传递到存储过程中,并尝试使用while循环将其添加。 I tried to use user defined type to define the array, but do not know how to pass it into the insert command 我试图使用用户定义的类型来定义数组,但是不知道如何将其传递给插入命令

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

This is the SQL/PL: 这是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

Consider changing your type to include both pairs. 考虑更改您的类型以包括两个对。

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

Then change your procedure to the following: 然后将您的过程更改为以下内容:

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

Then you can call your procedure as such. 然后,您可以这样调用过程。

declare @productPrices dbo.ProductPrices;

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

exec dbo.sp_create_order @productPrices;

Looks like you are learning table valued parameters , you should create a table valued parameter with two columns so that you can directly insert 看起来您正在学习表值参数,应该创建一个具有两列的表值参数,以便您可以直接插入

Here is one way to solve your current problem, where we can generate a sequence number using ROW_NUMBER and get a row value from both the tables 这是解决您当前问题的一种方法,我们可以使用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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM