Search code examples
c#sql-server.net-6.0smo

How to set a column's default value using Microsoft SMO?


I'm trying to set the default value of a non nullable bit column using Microsoft's SMO (C#) but I get an error on table creation.

Currently what I have is

if (!string.IsNullOrWhiteSpace(dynamicColumn.DefaultValue))
{
    column.Default = dynamicColumn.DefaultValue;
}

However when trying to create the table I get the following error:

One or more errors occured.

Create failed for Table'CustomDocument.TestDef9_Data'. An exception occurred while executing a Transact-SQL statement or batch. The default '((0))' does not exist.

I've tried ((0)), (0), and 0, and I get the same error every time.

Is there a different property I need to set on the column object or some other way to do it?


Solution

  • I was able to do it thusly (in powershell, but it's conceptually the same):

    $t = Get-DbaDbTable -SqlInstance . -Database tempdb -Table foo;
    # $t now holds a Table object
    $df = $t.columns['a'].AddDefaultConstraint('DF_foo_a');
    $df.Text = 0;
    $df.Create();