我正在尝试在数据库升级期间迁移数据,但我不明白为什么方案1正在运行但方案2正在抛出异常:
情景1
查询场景1:
-- NewTable already created
IF EXISTS(select * from sys.tables where name = 'NewTable')
AND EXISTS(select * from sys.tables where name = 'ObsoleteTable')
BEGIN
UPDATE newTable
SET newTable.Name = obsoleteTable.Name
FROM dbo.NewTable newTable
INNER JOIN dbo.ObsoleteTable obsoleteTable
ON obsoleteTable.Id = newTable.Id
END
-- ObsoleteTable will be removed after this step
场景2
查询场景2:
-- NewColumn has been created
IF EXISTS(select * from sys.columns where object_id = object_id('MyTable') AND name = 'ObsoleteColumn')
AND EXISTS(select * from sys.columns where object_id = object_id('MyTable') AND name = 'NewColumn')
BEGIN
UPDATE MyTable
SET NewColumn = ObsoleteColumn
END
-- Obsolete Column will be removed after this step
Msg 207,Level 16,State 1,Line 4 列名称“ObsoleteColumn”无效。
两种情况基本相同吗?如果存在过时的表/列,则仅迁移到新结构。否则忽略。
如果我在删除ObsoleteTable时执行方案1。它不会失败。那么为什么方案2会失败呢?
答案 0 :(得分:2)
这是一个经典错误,列ObsoleteColumn不存在。这意味着即使程序流从未到达该行
,查询也将失败这也将失败:
CREATE TABLE #xxx(a int)
IF 1 = 2
SELECT xyz FROM #xxx
为避免这种情况,您可以使用EXECUTE:
IF 1 = 2
EXEC('UPDATE MyTable SET NewColumn = ObsoleteColumn')