如何从MS SQL数据表中检索列默认值

我使用DataAdapter.FillSchema从MS SQL检索表的架构。 不幸的是,这不会返回列的默认值。 有没有办法以快速有效的方式检索此值作为模式的一部分,因为我需要检查数百个表?

谢谢!

默认值仅在行插入时确定。

作为替代方案,您可以使用Information_schema

 SELECT TABLE_NAME, COLUMN_NAME, COLUMN_DEFAULT FROM AdventureWorks2012.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Person'; 

请尝试以下查询:

 SELECT object_definition(default_object_id) AS definition FROM sys.columns WHERE name ='ColumnName' AND object_id = object_id('TableName') 

使用FillSchema无法做到这一点。 有关详细信息,请查看以下链接http://msdn.microsoft.com/en-us/library/229sz0y5.aspx

INFORMATION_SCHEMA是你应该看的地方。 INFORMATION_SCHEMA包含许多系统视图,可以显示数据库结构的详细信息。 例如

INFORMATION_SCHEMA.TABLES:显示数据库中的表列表INFORMATION_SCHEMA.COLUMNS:显示数据库的所有表中的列及其属性列表。 请查看以下位置了解更多详情。

http://msdn.microsoft.com/en-us/library/ms186778.aspx

要使用查询获取默认值,您可以使用以下查询:

 SELECT * FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = 'YourTableName' 

你应该尝试这样的东西来检索表模式。

 public partial class Form1 : Form { //create connectionString variable const string conString = @"Data Source=.\SQLEXPRESS; Initial Catalog=DBTest; Integrated Security=SSPI"; SqlConnection cn = null; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { this.getTableSchema(); } //function to get the schemas from the Tables in MSSQLSERVER private void getTableSchema() { try { cn = new SqlConnection(conString); cn.Open(); //call the getSchema Method of the SqlConnection Object passing in as a parameter the schema to retrieve DataTable dt = cn.GetSchema("tables"); //Binded the retrieved data to a DataGridView to show the results. this.dataGridView1.DataSource = dt; } catch (Exception) { throw; } } } 

编辑:关于conString的关闭引用