minhphien / migratordotnet

Automatically exported from code.google.com/p/migratordotnet
0 stars 0 forks source link

ChangeColumn Error When Setting Default Value to DB Function #74

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?
1. Add column to table without default
Database.AddColumn("MyTable", new Column("DateCreated", DbType.Date,
ColumnProperty.NotNull));
2. Change column to include default
Database.ChangeColumn("MyTable", new Column("DateCreated", DbType.Date,
ColumnProperty.NotNull, "GETDATE()"));
3.

What is the expected output? What do you see instead?

Expected to have the default of "MyTable.DateCreated" to be set to the
"GETEDATE()" function. 
Instead an error occurs:
Warning! : Incorrect syntax near the keyword 'DEFAULT'.
The SQL executing is
ALTER TABLE MyTable ALTER COLUMN DateCreated DATETIME NOT NULL DEFAULT
GETDATE() 

What version of the product are you using? On what operating system? With
what .NET implementation/version?
Migrator 0.7.0, Windows XP & XP64, .NET 3.5

What database and version are you seeing this issue on?
SQL Server 2005

Please provide any additional information below.
A quick work around (at least for SQL Server) is:
Database.ExecuteNonQuery("ALTER TABLE MyTable ADD DEFAULT GETDATE()
FOR DateCreated"); 

Original issue reported on code.google.com by jyoung1...@gmail.com on 13 Oct 2008 at 4:32

GoogleCodeExporter commented 9 years ago
I think making it (getdate()) will also make that work. Can you give that a 
shot?

Original comment by geoffl...@gmail.com on 14 Feb 2009 at 8:26

GoogleCodeExporter commented 9 years ago
Enclosing default value with parentheses does not solve the problem.

Here are convenient extension methods to deal with DEFAULT constraints.

    public static class TransformationProviderExtensions
    {
        public static void AddDefaultConstraint(this ITransformationProvider provider, String name, String table, String column, String defaultValue)
        {
            provider["SqlServer"].ExecuteNonQuery(String.Format("ALTER TABLE {0} ADD CONSTRAINT {2} DEFAULT {3} FOR {1}", table, column, name, defaultValue));
        }

        public static void RemoveDefaultConstraint(this ITransformationProvider provider, String name, String table)
        {
            provider["SqlServer"].ExecuteNonQuery(String.Format("ALTER TABLE {0} DROP CONSTRAINT {1}", table, name));
        }
    }

Then one could use it this way:

    Database.AddDefaultConstraint("ConstraintName", "TableName", "ColumnName", "(newid())");

Original comment by uksus70 on 31 May 2010 at 7:02