0

我们有一种 DDL 构造,有时(但不总是)会失败。构造是:

IF NOT EXISTS (SELECT 'b' 
               FROM   sys.COLUMNS A 
                      INNER JOIN sys.TABLES B 
                              ON A.OBJECT_ID = B.OBJECT_ID 
               WHERE  a.NAME = 'BadgeID' 
                      AND b.NAME = 'AllianceIncentBadges') 
  BEGIN 
      ALTER TABLE dbo.ALLIANCEINCENTBADGES 
        ADD BADGEID INT NOT NULL DEFAULT 0; 

      EXEC Sp_executesql 
N'MERGE INTO AllianceIncentBadges USING IncentiveBadges ON AllianceIncentBadges.BadgeName = IncentiveBadges.BadgeName WHEN MATCHED THEN UPDATE SET BadgeID = IncentiveBadges.BadgeID;'
    ; 
END; 

go 

如果我先运行“ALTER”表,然后运行“EXEC”,一切都很好。但是,如果我使用上述构造运行它,则不会添加 BadgeID 字段,并且 EXEC 会为缺少的列引发错误。我使用“EXEC”以便解析器不会抛出错误(如果在解析时列不存在,解析器将抛出错误)。

任何想法为什么会不时出现这个问题?

4

1 回答 1

1
BEGIN TRY
    ALTER TABLE dbo.AllianceIncentBadges ADD BadgeID int NOT NULL Default 0;
    MERGE INTO AllianceIncentBadges USING IncentiveBadges ON AllianceIncentBadges.BadgeName = IncentiveBadges.BadgeName WHEN MATCHED THEN UPDATE SET BadgeID = IncentiveBadges.BadgeID;
END TRY
BEGIN CATCH
    IF ERROR_NUMBER() <> '2705' THROW;
END CATCH
于 2013-07-31T16:45:49.207 回答