通常,您应该插入已确定ComputerReport
正确的行SFID
,而不是更新已插入的行。
INSERT INTO ComputerReport
(SFID, CrComputerName, CrLastUpdatedBy) -- add other columns as neeeded
SELECT SFID, 'JAMI-HP', 'JAMIE-HP\JAMIE'
FROM SoftwareReport
ComputerReport
如果表不包含任何有价值的东西,您可以截断表并执行上述插入。
否则,您需要一个光标跟随每个表,并SFID
根据光标位置第一个表中的值在光标位置的第二个表中SFID
设置。
在理想情况下,您刚刚创建了行,两个表中没有间隙,并且它们都包含相同数量的行,所以我们可以简单地写:
UPDATE ComputerReport
SET SFID = CRID
但在一般情况下,我们必须求助于更复杂的脚本:
DECLARE @sfid, @crid
DECLARE sfcursor READONLY
FOR SELECT SFID
FROM SoftwareReport
WHERE SFName IS NOT NULL
ORDER BY SFID ASC;
DECLARE crcursor
FOR SELECT CRID
FROM ComputerReport
-- WHERE SFID IS NULL
ORDER BY CRID ASC
FOR UPDATE SFID;
OPEN sfcursor;
OPEN crcursor;
FETCH NEXT FROM sfcursor INTO @sfid;
FETCH NEXT FROM crcursor INTO @crid;
-- update for each rows until we reach the end of either cursor
WHILE @@FETCH_STATUS = 0
BEGIN
UPDATE crcursor SET SFID = @sfid;
FETCH NEXT FROM sfcursor INTO @sfid
FETCH NEXT FROM crcursor INTO @crid
END
-- if there are remaining rows in sfcursor, insert new rows in ComputerReport
FETCH RELATIVE 0 FROM sfcursor INTO @sfid
WHILE @@FETCH_STATUS = 0
BEGIN
INSERT INTO ComputerReport (SFID) -- you should add the other columns here as needed
VALUES (@sfid);
FETCH NEXT FROM sfcursor INTO @sfid
END
CLOSE crcursor
CLOSE sfcursor
DEALLOCATE sfcursor
DEALLOCATE crcursor
如脚本中所示,您应该使用所需的列和值修改INSERT
查询以获取额外的行。ComputerReport
请注意,与常规(基于集合)查询相比,基于游标的脚本速度较慢。参考: