如何将多个id传递给存储过程

时间:2013-08-28 05:02:18

标签: sql sql-server stored-procedures sql-server-2008-r2

我在这样的商店程序中有一个查询:

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

现在我想从另一个存储过程执行这个存储过程,如下所示:

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

where  id in (selec id from table2)

我想将多个ID传递给SP。 我不想多次调用存储过程,使用游标或循环,我想避免它。

有人可以告诉我如何继续吗?

3 个答案:

答案 0 :(得分:2)

您可以使用XML作为Devart建议,但这里还有两个选项。

以逗号分隔的列表(您可以使用其他方法将其拆分,我在这里使用了转换为xml):

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

或用户定义的表类型:

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

请参阅sql fiddle demo,其中包含2个示例

答案 1 :(得分:1)

你可以直接在SP的定义中使用它

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

如果从表中获取这些id,只需声明一个#temp表或表变量

喜欢

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)

或者你可以直接在SP中使用你的table2

如果有任何帮助,请告诉我。

此致 Ashutosh Arya

答案 2 :(得分:1)

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