tags:

views:

570

answers:

2

Is there a way to determine a column's defaultvalue from the Sql Database using ado.net?

I tried using the SqlDataAdapter's FillSchema method:

 using (SqlDataAdapter adapter = new SqlDataAdapter()) {
    adapter.SelectCommand = myConnection.CreateCommand();
    adapter.SelectCommand.CommandType = CommandType.Text;
    adapter.SelectCommand.CommandText = "SELECT * FROM myTable";
    DataTable table = new DataTable();
    adapter.Fill(table);
    adapter.FillSchema(table, SchemaType.Mapped);
 }

When I inspect the DataColumns in the DataTable, I can determine if a column is an AutoIncrement, and can determine if it allows nulls using the AllowDBNull property. However, DefaultValue (for columns that I know have a default value) is always null.

I considered:

DataTable schemaTable = null;
using (SqlDataReader reader = adapter.SelectCommand.ExecuteReader(CommandBehavior.SchemaOnly)) {
   schemaTable = reader.GetSchemaTable();
   reader.Close();
}

but DefaultValue is not included in the schema.

So...how can I get a column's DefaultValue?

+2  A: 

Use this query to interrogate the INFORMATION_SCHEMA for the info you're looking for:

SELECT 
   TABLE_NAME, COLUMN_NAME, COLUMN_DEFAULT
FROM 
   INFORMATION_SCHEMA.COLUMNS
WHERE 
   TABLE_NAME = 'your table name' AND
   COLUMN_NAME = 'your column name'

Marc

marc_s
I think this implies an SQL Server (MSSQL), 2005(?) or above server, right?
mjv
No, any DB that supports the INFORMATION_SCHEMA should be supported. That's not just SQL Server - quite a few others support this as well. That's the big benefit of using INFORMATION_SCHEMA over SQL Server specific "sys.*" or "sysobjects" catalog views.
marc_s
As far as I know, at least MySQL, PostgreSQL and to a degree Oracle support INFORMATION_SCHEMA (not sure about IBM DB2)
marc_s
@Marc Good to know. I always considered these metadata objects as implementation specific. Thks.
mjv
Note that COLUMN_DEFAULT is not the actual value, but the expression to generate the default value. See my answer for more details.
Ruben
You're right - but it *could* be the actual default value, if you used a fixed value like "0". That does happen at times (like for "BIT" columns). But obviuosly, expression-based defaults aren't available as actual values.
marc_s
+1  A: 

Not really. This is because the default value can be determined at the time a record is inserted (like a GETDATE() or NEW_ID()). So the value cannot be determined in advance.

The COLUMN_DEFAULT column of INFORMATION_SCHEMA.COLUMNS gives you not the actual default value, but a string representation of the code SQL Server and the likes will execute to generate the default value. See http://msdn.microsoft.com/en-us/library/ms188348.aspx.

Having said that, simple constant values can easily be deduced from such an expression.

Ruben