简体   繁体   中英

Passing a list into a stored procedure

I have two lists of IDs that needs to be inserted into the database. 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. 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:

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

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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