"Invalid column name" error when using data migration scripts

时间:2017-10-12 09:50:11

标签: sql-server sql-server-data-tools dacpac

There's a couple data migration scripts in my SSDT project.

First one stores data from one table to another temporary table:

IF EXISTS 
(
    SELECT * 
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE table_name = N'DocumentEvent'
    AND column_name = N'Thumbprint'
)
BEGIN
    IF NOT EXISTS
    (
        SELECT * FROM INFORMATION_SCHEMA.TABLES 
        WHERE TABLE_NAME = N'tmp_DocumentEventCertificates'
    )
    BEGIN
        CREATE TABLE tmp_DocumentEventCertificates
        (
            [EventId] UNIQUEIDENTIFIER NOT NULL,
            [Thumbprint] nvarchar(100)
        )
    END

    INSERT INTO
        tmp_DocumentEventCertificates
    SELECT
        [EventId],
        [Thumbprint]
    FROM
        [DocumentEvent]
    WHERE
        [Thumbprint] IS NOT NULL
END

Second one transfers data from temporary table to another table:

IF EXISTS
(
    SELECT * FROM INFORMATION_SCHEMA.TABLES 
    WHERE TABLE_NAME = N'tmp_DocumentEventCertificates'
)
BEGIN
    UPDATE
        [DocumentAttachment]
    SET
        [DocumentAttachment].[Certificate_Thumbprint] = tmp.[Thumbprint]
    FROM
        tmp_DocumentEventCertificates AS tmp
    WHERE
        ([DocumentAttachment].[EventId] = tmp.[EventId]) AND
        ([DocumentAttachment].[ParentDocumentAttachmentId] IS NOT NULL)

    DROP TABLE tmp_DocumentEventCertificates
END

Column [Thumbprint] is being removed from [DocumentEvent] table.
Column [Certificate_Thumbprint] is being added to [DocumentAttachment] table.

Data must be transferred from [DocumentEvent].[Thumbprint] to [DocumentAttachment].[Certificate_Thumbprint].

These scripts works as expected, when database is in the state, which requires migration from above, that is, [DocumentEvent].[Thumbprint] exists, and [DocumentAttachment].[Certificate_Thumbprint] does not exist.

But when database is migrated, all attempts to deploy dacpac fail because of "Invalid column name 'Thumbprint'" error.

I'm almost sure, that this happens because SQLCMD tries to compile deploy script in whole, and this could be done successfully only when [DocumentEvent].[Thumbprint] exists.

But what is the workaround?

Looks like IF EXISTS in first script can't help.

1 个答案:

答案 0 :(得分:4)

Yes you are right, it's compilation error. If the column does not exist your script cannot be compiled. IF Exists and other data flow constructions are not analyzed.

You should wrap your code producing compilation error in EXEC:

exec(
'INSERT INTO
        tmp_DocumentEventCertificates
    SELECT
        [EventId],
        [Thumbprint]
    FROM
        [DocumentEvent]
    WHERE
        [Thumbprint] IS NOT NULL')