SQL 2005
我有一个名为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(这些是存储过程的参数)。 / p>
我有以下似乎有效:
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的同时,我想将新记录的TimeStamp更新为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“。
感谢所有人的帮助。
答案 0 :(得分: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