0

我正在尝试在 SQL 中插入一个列表。我从 TableName1 和 TableName2 的 JOIN 查询中获得了两列值的列表。通过 ProductId 的计数,我将 ProductId 和 Quantity 插入 Table3。但是插入失败,因为 ProductId 为空。我从 Join 查询中得到 ProductId 和 Quantity 的两个值,如下所示。如何将此列表插入 Table3 中?

列表

ProductId  Quantity 
56           1
58           2   

SQL:

DECLARE @productid int 
DECLARE @quantity int 

SET @productid  = SELECT A.[ProductId],
A.[Quantity] FROM [TableName1] A
INNER JOIN [TableName2] B
ON A.[OrderId] = B.[OrderId]  WHERE B.[CustomerId] = 1 AND A.[OrderId] = 68


SET @quantity  = SELECT 
A.[Quantity] FROM [TableName1] A
INNER JOIN [TableName2] B
ON A.[OrderId] = B.[OrderId]  WHERE B.[CustomerId] = 1 AND A.[OrderId] = 68


DECLARE @i int = 0
DECLARE @pcount int =  (SELECT COUNT(ProductId) FROM [TableName1] A
INNER JOIN [TableName2] B
ON A.[OrderId] = B.[OrderId]  WHERE B.[CustomerId] = 1 AND
 A.[OrderId] = 68)

WHILE @i <= @pcount 

BEGIN   

    SET @i = @i + 1

    DECLARE @productname nvarchar(MAX)
    SET @productname = (SELECT [ProductName] FROM [TableName4] WHERE [ProductId]= @productid)


    DECLARE @PRate decimal
    SET @PRate =(SELECT [SpecialPrice] FROM [TableName5] 
    WHERE [ProductId]=@productid)


    DECLARE @SPrice decimal
    SET @SPrice = @PRate * @quantity

    INSERT INTO [Table3]
    [ProductId],[ProductName],[Quantity],[Price],[TotalAmount]) 
    VALUES
    (@productid,@productname,@quantity,@PRate,@SPrice)
END

如何将循环中的 productid 和数量传递给 Table3 以进行插入。
循环时我的代码中有任何错误吗?

4

1 回答 1

2

你最好把它写成一个基于集合的操作:

WITH pq AS
(
    SELECT
     A.[ProductId]
    ,A.[Quantity]
    ,D.[ProductName]
    ,E.[SpecialPrice]
    ,E.[SpecialPrice]*A.[Quantity] AS SPrice
    FROM [TableName1] A
    INNER JOIN [TableName2] B
    ON A.[OrderId] = B.[OrderId]
    INNER JOIN [TableName4] D
    ON A.[ProductId] = D.[ProductId]
    INNER JOIN [TableName5] E
    ON A.[ProductId] = D.[ProductId]
    WHERE B.[CustomerId] = 1 
    AND A.[OrderId] = 68
)
INSERT INTO [Table3]
([ProductId]
,[ProductName]
,[Quantity]
,[Price]
,[TotalAmount])
SELECT
 [ProductId]
,[ProductName]
,[Quantity]
,[SpecialPrice]
,SPrice
FROM pq;
于 2013-08-27T14:44:44.133 回答