2012-12-03 66 views
0

SQL 2005如何從INSERT語句運行子查詢?

我有一個名爲tPieceTable其佈局是像下表:

ID BatchNo PieceNo 
----------------------- 
1 abc  123 
2 xyz  321 

在tPieceTable, 「ID」 是一個IDENTITY(1,1)。

我也有另一個表(tLiveTable),它具有以下佈局。

ID TimeStamp LocationRef 
--------------------------- 

我所試圖做的是創建一個存儲過程,將插入來自tPieceTable INTO tLiveTable的ID,其中BatchNo等於@BatchNo和PieceNo等於@PieceNo(這些參數的存儲程序)。

我有這似乎是工作如下:

CREATE PROCEDURE spSetLocationChargeTable 
    @BatchNo nvarchar(50), 
    @PieceNo nvarchar(50) 
AS 
    INSERT INTO tLiveTable(PieceID) 
    SELECT ID FROM tPieceTable 
    WHERE tPieceTable.BatchNo = @BatchNo AND tPieceTable.PieceNo = @PieceNo 
GO 

現在,在同一時間作爲INSERT,我想更新的時間戳新紀錄GETDATE(),和LocationRef我要插入以下查詢的輸出:

SELECT ID FROM tLocationRefs WHERE Equipment = 'CHARGE_TABLE' 

僅供參考tLocationRefs看起來是這樣的:

ID Equipment  Description 
------------------------------ 
0 CHARGE_TABLE Charger Machine Table 

我在哪裏掙扎是如何將所有這一切合併爲一個INSERT。我試着做一個插入後跟兩個UPDATE,但我不能引用tPieceTable,例如有以下幾點:

CREATE PROCEDURE spSetLocationChargeTable 
    @BatchNo nvarchar(50), 
    @PieceNo nvarchar(50) 
AS 
    INSERT INTO tLiveTable(PieceID) 
    SELECT ID FROM tPieceTable 
    WHERE tPieceTable.BatchNo = @BatchNo AND tPieceTable.PieceNo = @PieceNo 

    UPDATE tLiveTable 
    SET TimeStamp = GetDate() 
    WHERE tPieceTable.BatchNo = @BatchNo AND tPieceTable.PieceNo = @PieceNo 

    UPDATE tLiveTable 
    SET LocationRef = (SELECT ID FROM tLocationRefs WHERE Equipment = 'CHARGE_TABLE') 
    WHERE BatchNo = @BatchNo AND PieceNo = @PieceNo 
GO 

我得到: -

「的多部分標識符 」tPieceTable.BatchNo「 可能不會被發現。」 「 」無法找到多部分標識符「tPieceTable.PieceNo」。「

感謝大家的幫助。

回答

1
INSERT INTO tLiveTable 
     (PieceID, TimeStamp, LocationRef) 
SELECT ID 
,  getdate() 
,  (
     SELECT ID 
     FROM tLocationRefs 
     WHERE Equipment = 'CHARGE_TABLE' 
     ) 
FROM tPieceTable 
WHERE tPieceTable.BatchNo = @BatchNo 
     AND tPieceTable.PieceNo = @PieceNo