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

130 views Asked by At

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?

2

There are 2 answers

0
Ben Thul On BEST ANSWER

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();
1
Adalyat Nazirov On

You have to use DefaultConstraint property instead. Here a snippet

if (!string.IsNullOrWhiteSpace(dynamicColumn.DefaultValue))
{
    column.DefaultConstraint = new DefaultConstraint(table, "DF_TestDef9_Data_ColumnName");
    column.DefaultConstraint.Text = "(0)";
}