我对SQL很陌生......寻找一个简单的解决方案。我有一个查询,我在其中声明了一个外键列表,如下所示:
DECLARE @CustomerFkList table (Fk int);
BEGIN
INSERT @CustomerFkList (Fk) VALUES (12345), (67890), (65432)
END
稍后在查询中我想将一条记录插入到列表中每个值的特定表中,其中外键值进入外键字段。对此最好的方法是什么?
这是完整的代码 - 到目前为止我所拥有的。我知道最后两行是错误的:
USE CustomerDatabase;
DECLARE @CustomerFkList table (Fk int);
BEGIN
INSERT @CustomerFkList (Fk) VALUES (x), (x), (x), (etc.)
END
BEGIN
UPDATE CustomerLifeCycleStatus SET EndDate=GETDATE()
WHERE (CustomerFk IN (SELECT Fk FROM @CustomerFkList)
AND LifeCycleStatus = 'Active'
AND EndDate IS NULL)
END
/* ------- below is what I need to iterate through ---------- */
INSERT INTO CustomerLifeCycleStatus (CustomerFk, LifeCycleStatus, StartDate)
VALUES (@CustomerFkList, 'Retired', GETDATE());
请帮忙吗? (我使用的是SQL-Server 2008 R2,Microsoft SQL Server Management Studio)
答案 0 :(得分:2)
无需迭代,只需将其全部插入一个语句:
INSERT INTO CustomerLifeCycleStatus (CustomerFk, LifeCycleStatus, StartDate)
SELECT FK, 'Retired', GETDATE()
FROM @CustomerFKList