开发者

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

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 c开发者_如何学JAVAan 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?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜