5

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 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

6 Comments

I think this implies an SQL Server (MSSQL), 2005(?) or above server, right?
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.
As far as I know, at least MySQL, PostgreSQL and to a degree Oracle support INFORMATION_SCHEMA (not sure about IBM DB2)
@Marc Good to know. I always considered these metadata objects as implementation specific. Thks.
Note that COLUMN_DEFAULT is not the actual value, but the expression to generate the default value. See my answer for more details.
|
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.