开发者

SQL script runs fine on one database, errors on another

We have a script that must allow for being re-run several times.

We have an MS-SQL script that updates a table if a (now obsolete) column exists, then deletes the column. To ensure that the script can be run several times, it first checks for the existence of a column before performing the updates.

The script works as expected on our dev database, updating the data on the first run, then displaying the message 'Not updating' on subsequent runs.

On our test database the script runs fine on the first run, but errors with "Invalid column name 'OldColumn'" on subsequent runs; if开发者_Python百科 I comment out the UPDATE and ALTER statements it runs as expected.

Is there a way to force the script to run even if there's a potential error, or is it something to do with how the database was set-up? (fingers crossed I'm not looking like a complete noob!)

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'MyTable' AND COLUMN_NAME = 'OldColumn')

    BEGIN
        PRINT 'Updating and removing old column...'
        UPDATE MyTable SET NewColumn='X' WHERE OldColumn=1;
        ALTER TABLE MyTable DROP COLUMN OldColumn;
    END

ELSE
    PRINT 'Not updating'
GO


As a work around you could do

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'MyTable' AND COLUMN_NAME = 'OldColumn')
    BEGIN
        PRINT 'Updating and removing old column...'
        EXEC ('UPDATE MyTable SET NewColumn=''X'' WHERE OldColumn=1;');
        ALTER TABLE MyTable DROP COLUMN OldColumn;
    END

ELSE
    PRINT 'Not updating'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜