Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I retrieve DataColumn.DefaultValue from a Sql Table?

Tags:

c#

.net

ado.net

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?

like image 393
C-Pound Guru Avatar asked Oct 16 '09 20:10

C-Pound Guru


People also ask

What is a default value in SQL?

The DEFAULT constraint is used to set a default value for a column. The default value will be added to all new records, if no other value is specified.


2 Answers

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

like image 102
marc_s Avatar answered Oct 17 '22 21:10

marc_s


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.

like image 40
Ruben Avatar answered Oct 17 '22 19:10

Ruben