SQL IF statement is being ignored

前端 未结 2 770
悲&欢浪女
悲&欢浪女 2021-01-22 00:50

I have a long script and I like to be able to just run the whole file when I need to and not worry about if parts of it have already ran. But the script below is giving me probl

2条回答
  •  梦毁少年i
    2021-01-22 01:13

    Martin was definitely onto something. The stuff inside the IF is being treated by the parser at parse time and ignoring whether your IF will pan out. This is the same reason you can't do:

    IF 1 = 1
      CREATE TABLE #x(a INT);
    ELSE
      CREATE TABLE #x(b INT);
    

    One workaround would be to use dynamic SQL:

    IF EXISTS ...
    BEGIN
      BEGIN TRANSACTION;
    
      DECLARE @sql NVARCHAR(MAX);
    
      SET @sql = N'
            DELETE FROM [dbo].[Notes]
            WHERE [EntityId] IS NULL 
            AND [EntityType] IS NULL
            --Delete notes where the corresponding contact or account has been deleted.
            OR [ID] IN (9788, 10684, 10393, 10718, 10719)
    
            --Populate new columns with all existing data
            UPDATE [dbo].[Notes]
            SET [AccountId] = [EntityId]
            WHERE [EntityType] = 1
    
            UPDATE [dbo].[Notes]
            SET [ContactId] = [EntityId]
            WHERE [EntityType] = 2
    
            --Delete EntityId and EntityType columns from the Notes table
            ALTER TABLE [dbo].[Notes]
            DROP COLUMN [EntityId], [EntityType]';
    
        EXEC sp_executesql @sql;
    
        COMMIT TRANSACTION;
    END
    

    But you still should be sure that both columns are there.

提交回复
热议问题