Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deleting a column with a default value throws an error in SQL Server #4

Open
shawng opened this issue Mar 25, 2010 · 0 comments
Open

Comments

@shawng
Copy link

shawng commented Mar 25, 2010

Deleting a column with a default value throws an error in SQL Server, since SQL Server creates a default constraint to enforce the default value. If you are dropping a column, you don't need the default value constrain anymore either, so it should be safe to delete. Here's some code to do it (replace line 71 of SqlServerGenerator.cs with this, if it isn't horribly mangled by the editor):

public override string Generate(DeleteColumnExpression expression)
{
// before we drop a column, we have to drop any default value constraints in SQL Server
string sql = @"
DECLARE @default sysname, @SQL nvarchar(max);

    -- get name of default constraint
    SELECT @default = name 
    FROM sys.default_constraints 
    WHERE parent_object_id = object_id('{0}')
    AND type = 'D'
    AND parent_column_id = (
        SELECT column_id 
        FROM sys.columns 
        WHERE object_id = object_id('{0}')
        AND name = '{1}'
    );

    -- create alter table command as string and run it
    SET @sql = N'ALTER TABLE [{0}] DROP CONSTRAINT ' + @default;
    EXEC sp_executesql @sql;

    -- now we can finally drop column
    ALTER TABLE [{0}] DROP COLUMN [{1}];";

return FormatExpression(sql, expression.TableName, expression.ColumnName);

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant