How to retrieve column default value from MS SQL data table

☆樱花仙子☆ 提交于 2019-12-10 16:39:49

问题


I am using DataAdapter.FillSchema to retrieve tables' schema from MS SQL. Unfortunately this doesn't return the default value for the columns. Is there a way to retrieve this value as part of the schema in a fast and efficient way as I need to examine hundreds of tables?

Thanks!


回答1:


Default value is determined at the time of row insertion only.

As an alternative, you can utilize Information_schema

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



回答2:


Try the following query:

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



回答3:


There is no way you can do that by using FillSchema. For details check link below http://msdn.microsoft.com/en-us/library/229sz0y5.aspx

INFORMATION_SCHEMA is the place where you should look. INFORMATION_SCHEMA contains many system views which can show you details of database structure. for example

INFORMATION_SCHEMA.TABLES : shows you list of tables in the database INFORMATION_SCHEMA.COLUMNS : shows you list of Columns and their attributes in all tables of the database. Please look at following location for more detail.

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

To get default value using query you can use following query:

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



回答4:


you should try something like this to retrieve tables schema.

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


}

EDIT: Close quote on conString



来源:https://stackoverflow.com/questions/10314483/how-to-retrieve-column-default-value-from-ms-sql-data-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!