插入n行存储过程

时间:2013-06-14 21:30:31

标签: sql sql-server tsql stored-procedures

尝试根据传递的参数插入多行。

试过这个并且只重复了一次:

ALTER PROCEDURE [dbo].[ActivateCertificates]

    @Count              int,
    @CertificateNumber  int,
    @Buyer              VarChar(50)


AS
Declare @x int
Declare @InitialCharacter   Char(1)
SET @InitialCharacter='C'
Declare @Last3      Char(3)
SET @Last3='867'

    while @x <= @Count 
begin
    /* CREATE THE CERTIFICATE NUMBER */
    set @CertificateNumber = @CertificateNumber +1
    /* insert into certificates  cert number and who sold to. */
    INSERT into Certificates (CertificateNumber,Buyer) 
    VALUES (@InitialCharacter + ltrim(rtrim(cast(@CertificateNumber as char))) + @Last3, @Buyer) 
end 
set @x =@x + 1


GO

2 个答案:

答案 0 :(得分:1)

您的变量在BEGIN/END块之外递增。另外,我建议您最初将变量设置为0,以避免存储在该内存位置的任何潜在垃圾数据。

答案 1 :(得分:0)

要使用基于集合的查询而不是循环来实现您的目标( BTW,StackOverflow 上有很多此类示例),您必须拥有一个计数(数字)表或创建它带有子查询或递归CTE。

CREATE TABLE tally (id INT NOT NULL PRIMARY KEY);

将其填充到100000(Celko-style

INSERT INTO tally (id) 
SELECT a.N + b.N * 10 + c.N * 100 + d.N * 1000 + e.N * 10000 + 1 as N
  FROM (select 0 as N union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) a
      , (select 0 as N union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) b
      , (select 0 as N union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) c
      , (select 0 as N union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) d
      , (select 0 as N union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) e
ORDER BY N;

现在,您的存储过程归结为一个语句

CREATE PROCEDURE ActivateCertificates
  @Count              INT,
  @CertificateNumber  INT,
  @Buyer              VARCHAR(50)
AS
INSERT INTO Certificates (CertificateNumber, Buyer) 
SELECT 'C' + CAST(q.number + t.id AS VARCHAR(12)) + '867', q.buyer 
  FROM
( 
  SELECT @CertificateNumber number, @Buyer buyer
) q, tally t
WHERE t.id <= @Count;

这是 SQLFiddle 演示

现在,如果您生成相对少量的证书(&lt; 32768),那么您可以使用递归CTE来构建一系列数字(并且不需要持久的计数表)

CREATE PROCEDURE ActivateCertificates
  @Count              INT,
  @CertificateNumber  INT,
  @Buyer              VARCHAR(50)
AS
WITH tally AS (
  SELECT 1 id
  UNION ALL
  SELECT id + 1 FROM tally WHERE id < @Count
)
INSERT INTO Certificates (CertificateNumber, Buyer) 
SELECT 'C' + CAST(q.number + t.id AS VARCHAR(12)) + '867', q.buyer 
  FROM
( 
  SELECT @CertificateNumber number, @Buyer buyer
) q, tally t OPTION (MAXRECURSION 32767);

此案例的 SQLFiddle 演示