使用循环批量插入

时间:2017-04-07 02:50:40

标签: sql-server

我一直在尝试将500条记录插入表格(dbo.Product),但我收到此错误:

  

Msg 102,Level 15,State 1,Line 31
  'p'

附近的语法不正确

这是我的问题:

DECLARE @StartLoop INT,
        @EndLoop INT,
        @ProductID INT,
        @ProductName NVARCHAR(250),
        @BestBefore DATETIME,
        @ManufactureDate datetime,
        @ProductNumber NVARCHAR(25),
        @Weight decimal, 
        @ProductStockLevelID INT 

SELECT 
    @StartLoop =1,
    @EndLoop = 500,
    @ProductID  = '',
    @ProductName = 'Yoghurt',
    @BestBefore = '',
    @ManufactureDate = '' ,
    @ProductNumber = '',
    @Weight = '', 
    @ProductStockLevelID = ''

WHILE @StartLoop <= @EndLoop
BEGIN
    INSERT INTO dbo.Product p (ProductID, ProductName, BestBefore, ManufactureDate, ProductNumber, [Weight], ProductStockLevelID)
        SELECT 
            @ProductID  + CAST(@StartLoop AS INT),
            @ProductName + Cast(@startloop AS  NVARCHAR(250)),
            @BestBefore + CAST(@StartLoop AS DATETIME),
            @ManufactureDate + CAST(@startLoop AS DATETIME),
            @ProductNumber + CAST(@StartLoop AS Nvarchar(25)),
            @Weight + CAST(@StartLoop AS DECIMAL),
            @ProductStockLevelID + CAST(@StartLoop AS INT)

    SELECT @StartLoop = @StartLoop + 1 
END 

有人可以告诉我我做错了吗?

提前谢谢。

2 个答案:

答案 0 :(得分:1)

删除插入命令中的p

INSERT INTO dbo.Product p (ProductID

INSERT INTO dbo.Product (ProductID

参考链接INSERT SQL MDSN

另一种在没有WHILE的情况下插入产品表的方法是使用CTErecursive function

 ;WITH temp AS 
(
  SELECT @StartLoop AS RowIndex 
  UNION ALL 
  SELECT t.RowIndex + 1
  FROM temp t
  where t.RowIndex < @EndLoop
) -- temp table result @StartLoop,@StartLoop +1 ,... -> @EndLoop 

INSERT INTO dbo.Product (ProductID, ProductName, BestBefore, ManufactureDate, ProductNumber, [Weight],ProductStockLevelID)
SELECT 
   @ProductID  + CAST(t.RowIndex AS INT),
   @ProductName + Cast(t.RowIndex AS  NVARCHAR(250)),
   @BestBefore + CAST(t.RowIndex AS DATETIME),
   @ManufactureDate + CAST(t.RowIndex AS DATETIME),
   @ProductNumber + CAST(t.RowIndex AS Nvarchar(25)),
   @Weight + CAST(t.RowIndex AS DECIMAL),
   @ProductStockLevelID + CAST(t.RowIndex AS INT)
FROM temp t
OPTION (MAXRECURSION 0 )

答案 1 :(得分:0)

您应该从{<1}}中删除:

p

让它像这样:

INSERT INTO dbo.Product p (ProductID