在存储过程中将Create类型作为表参数循环

时间:2014-06-05 10:03:04

标签: sql sql-server stored-procedures

我正在开发一个存储过程来在表中插入一组代码。我正在使用SQL SERVER 2012 SP1 Express版。

我已经这样做了将数组传递给存储过程:

CREATE TYPE dbo.ChildsCodeList
AS TABLE
(
  CODE nvarchar(20)
);
GO

这是我的存储过程:

create procedure dbo.MyStoredProdure
    @childs as dbo.ChildsCodeList READONLY,
    @parentCode nvarchar(20)
as
begin

[ ... ]

end
go

如何循环@childs

我必须在具有增量值的表中插入该代码,但在这种情况下,我不能使用标识列。

我将在此表中插入这些代码:

  CODE   |  POSITION
---------+----------
         |

2 个答案:

答案 0 :(得分:1)

写为:

CREATE PROCedure dbo.MyStoredProdure
    @childs as dbo.ChildsCodeList READONLY
    AS    
    SET NOCOUNT ON
    INSERT INTO tbl_test
    -- since no ordering is to be done among rows use 'Select 1'
    SELECT CODE,row_number() over (order by (select 1 )) as Rownum
    FROM   @childs

GO

您可以在此处逐步找到详细的Demo

答案 1 :(得分:0)

row_number(),可能。

insert sometable (code, position)
select code, row_Number() over (order by something) from  @childs