I need to find the default value of a column in a SQL Server 2005 or 2008 database from .Net.
My first attempt was to execute the stored procedure:
sp_help @objname
Where @objname
is the table. Then in the seventh table returned (the constraints table), I was going to use the value in constraint_keys
for the default constraints. When I run this query from SQL Server Management Studio it behaves as intended, but when I run it from C# code, the column constraint_keys
was null (although all the other columns were populated).
My second attempt was to use:
SELECT name, [text]
FROM syscomments com
INNER JOIN syscolumns col ON com.id = col.cdefault
WHERE col.id = object_id(@Table)
AND col.cdefault > 0
Which also works fine in SQL Server Management Studio. When I run it from .Net, however, it returns no rows.
Additional:
Example .Net code (using Enterprise Libraries):
private DataTable GetDefaults(string tablename string database)
{
var db = DatabaseEL.Create(database);
string sql = @"
SELECT name, [text]
FROM syscomments com
INNER JOIN syscolumns col ON com.id = col.cdefault
WHERE col.id = object_id(@Table)
AND col.cdefault > 0";
using (var command = db.GetSqlStringCommand(sql))
{
db.AddInParameter(command, "@Table", DbType.String, tablename);
return db.ExecuteDataTable(command);
}
}
Note that I have now also tried each of the following from the linked similar question:
SELECT
name, object_definition(default_object_id) AS default_value
FROM sys.columns
WHERE object_id = object_id(@Table)
AND default_object_id != 0
and
SELECT
sc.name AS column_name,
sm.text AS default_value
FROM sys.sysobjects so
JOIN sys.syscolumns sc ON sc.id = so.id
LEFT JOIN sys.syscomments SM ON sm.id = sc.cdefault
WHERE so.xtype = 'U'
AND SO.name = @Table
AND sm.text IS NOT NULL
They both worked in SSMS, but in .Net, the former had nulls in the default_value
column, and the latter had no rows.