简体   繁体   中英

How to pass more than one id to stored procedure

I have a query in a store procedure like this:

CREATE PROCEDURE DELETEREP (@id INT) 
AS 
    DELETE FROM TABLE 
    WHERE  ID = @id 

Now I want to execute this store procedure from another stored procedure like this:

exec(Deleterep) from here i want to pass multiple ids like 

where  id in (selec id from table2)

I want to pass multiple ids to the SP. I don't want to call store procedure multiple time, using cursor or loop, I want to avoid it.

Can someone give me an idea of how to proceed?

you can use XML as Devart suggested, but here's two more options.

Comma separated list (you can split it with other methods, I've used convert to xml just here):

create procedure usp_test1(@list nvarchar(max))
as
begin
    declare @data xml

    select @data = cast('<id>' + replace(@list, ', ', '</id><id>') + '</id>' as xml)

    select *
    from test
    where id in
      (
          select t.c.value('.', 'int') as a
          from @data.nodes('id') as t(c)
      )
end

or user-defined table type:

create type list as table (id int primary key)

create procedure usp_test2(@list list readonly)
as
begin
    select *
    from test
    where id in (select id from @list)
end

see sql fiddle demo with 2 examples

you can directly use this in definition of SP

CREATE PROCEDURE DELETEREP (@id INT,@id1 int,@id2 int) 
AS 
    DELETE FROM TABLE 
    WHERE  ID in (@id,@id1,@id2)

If you are taking these id's from table just declare a #temp table or table variable

Like

CREATE PROCEDURE DELETEREP 

AS 

    Declare @TEMP_TABLE TABLE ( ID INT)

    INSERT INTO @TEMP_TABLE select id from table2

        DELETE FROM TABLE 
        WHERE  ID in (SELECT ID FROM @TEMP_TABLE)

OR YOU CAN Directly use your table2 in SP

Please let me know if this is of any help.

Regards, Ashutosh Arya

Try this one -

CREATE PROCEDURE dbo.usp_DELETEREP 
(
    @XML XML
) 
AS BEGIN

    DELETE FROM dbo.[TABLE] 
    WHERE ID IN (
        SELECT t.c.value('.', 'BIGINT')
        FROM @XML.nodes('/data/id') t(c)
    )

END

GO

DECLARE @XML XML
SELECT @XML = '
<data>
    <id>1</id>
    <id>2</id>
</data>'

EXEC usp_DELETEREP @XML = @XML

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