我正在使用DataAdapter.FillSchema
从 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