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

Dan*_*iel 4 c# dataadapter database-schema

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

谢谢!

Adi*_*dil 7

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

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

SELECT TABLE_NAME, COLUMN_NAME, COLUMN_DEFAULT
FROM AdventureWorks2012.INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Person';
Run Code Online (Sandbox Code Playgroud)


Nud*_*ena 0

您应该尝试类似的方法来检索表架构。

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;
        }
    }


}
Run Code Online (Sandbox Code Playgroud)

编辑:关闭 conString 的引用