如何将此功能转换为sql server功能?

时间:2013-05-13 21:01:34

标签: sql-server tsql function

我不是TSQL的专家,我有这个功能:

for (i=1;i<=30;i++) {
    for (j=1;j<=10;j++){
        insert into NAMES values ("","","Name"+i+" - fn"+j", "Name"+i+" - fn"+j", "Numeric", "R",0,"N",0,"00");
     }
}

我想将其转换为SQL函数,以便一次插入所有300条记录(30x10)。

2 个答案:

答案 0 :(得分:5)

您无法对某项功能执行INSERT。如果我理解正确,这就是你想要的:

DECLARE @I INT, @J INT
SET @I = 1
SET @J = 1

WHILE @I <= 30
BEGIN
    WHILE @J <= 10
    BEGIN
        INSERT INTO NAMES
        SELECT  '',
                '',
                'Name'+CAST(@I AS VARCHAR(2))+' - fn'+CAST(@J AS VARCHAR(2)),
                'Name'+CAST(@I AS VARCHAR(2))+' - fn'+CAST(@J AS VARCHAR(2)),
                'Numeric',
                'R',
                0,
                'N',
                0,
                '00'

        SET @J = @J + 1
    END
    SET @J = 1
    SET @I = @I + 1
END

答案 1 :(得分:3)

您还可以使用数字表来避免需要循环。

WITH
  L0       AS(SELECT 1 AS c UNION ALL SELECT 1),
  L1       AS(SELECT 1 AS c FROM L0 AS A CROSS JOIN L0 AS B),
  L2       AS(SELECT 1 AS c FROM L1 AS A CROSS JOIN L1 AS B),
  L3       AS(SELECT 1 AS c FROM L2 AS A CROSS JOIN L2 AS B),
  L4       AS(SELECT 1 AS c FROM L3 AS A CROSS JOIN L3 AS B),
  Nums     AS(SELECT  TOP(300) ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS n FROM L4),
  IJ(i,j)  AS(SELECT CAST(1 + n%30 AS VARCHAR(2)), CAST(1 + n%10 AS VARCHAR(2))  FROM Nums)
 INSERT INTO NAMES  
SELECT '',
       '',
       'Name' + i + ' - fn' + j, 
       'Name' + i + ' - fn' + j,
       'Numeric', 
       'R',
       0,
       'N',
       0,
       '00'
 FROM IJ;