SQL Server:使用查询查找列的默认值

时间:2022-01-07 07:22:51

How can I find out the default value of a column in a table using a SQL query?

如何使用SQL查询找出表中列的默认值?

By using this stored procedure:

通过使用此存储过程:

sp_columns @tablename 

I get some information on the columns of a particular table but the default value of the columns is missing, How can I get it?

我得到了一些特定表的列的信息,但缺少列的默认值,我怎么能得到它?

3 个解决方案

#1


49  

You can find the stored definition with the below (remember to adjust the column and table name to find to be ones relevant to your environment!)

您可以使用以下内容找到存储的定义(请记住调整列和表名称以找到与您的环境相关的名称!)

SELECT object_definition(default_object_id) AS definition
FROM   sys.columns
WHERE  name      ='colname'
AND    object_id = object_id('dbo.tablename')

#2


14  

Use:

使用:

   SELECT so.name AS table_name, 
          sc.name AS column_name, 
          sm.text AS default_value
     FROM sys.sysobjects so
     JOIN sys.syscolumns sc ON sc.id = so.id
LEFT JOIN sys.syscomments sm ON sm.id = sc.cdefault
    WHERE so.xtype = 'U' 
      AND so.name = @yourtable
 ORDER BY so.[name], sc.colid

#3


7  

I use INFORMATION_SCHEMA:

我使用INFORMATION_SCHEMA:

SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, COLUMN_DEFAULT
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = @SchemaName 
  AND TABLE_NAME = @TableName
  AND COLUMN_NAME = @ColumnName

#1


49  

You can find the stored definition with the below (remember to adjust the column and table name to find to be ones relevant to your environment!)

您可以使用以下内容找到存储的定义(请记住调整列和表名称以找到与您的环境相关的名称!)

SELECT object_definition(default_object_id) AS definition
FROM   sys.columns
WHERE  name      ='colname'
AND    object_id = object_id('dbo.tablename')

#2


14  

Use:

使用:

   SELECT so.name AS table_name, 
          sc.name AS column_name, 
          sm.text AS default_value
     FROM sys.sysobjects so
     JOIN sys.syscolumns sc ON sc.id = so.id
LEFT JOIN sys.syscomments sm ON sm.id = sc.cdefault
    WHERE so.xtype = 'U' 
      AND so.name = @yourtable
 ORDER BY so.[name], sc.colid

#3


7  

I use INFORMATION_SCHEMA:

我使用INFORMATION_SCHEMA:

SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, COLUMN_DEFAULT
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = @SchemaName 
  AND TABLE_NAME = @TableName
  AND COLUMN_NAME = @ColumnName