我正在编写一个分析数据库表的脚本,我在从SQL Server 2005获取列的默认值时遇到问题。
以下在SQL Server 2008上运行良好,但是当我在SQL Server 2005上运行相同的东西时,结果是一个空字符串,我无法弄清楚原因。
DECLARE @sDatabase VARCHAR(100);
DECLARE @sTable VARCHAR(100);
DECLARE @sColumn VARCHAR(100);
SET @sDatabase = 'SomeDatabase';
SET @sTable = 'tbl_something';
SET @sColumn = 'SomethingID';
SELECT
syscolumns.name AS column_name,
systypes.name column_type,
syscolumns.length AS column_length,
syscolumns.prec AS column_precision,
syscolumns.scale AS column_scale,
syscolumns.isnullable AS column_nullable,
syscomments.text AS column_default_value -- Should be default value!
FROM
sysobjects
INNER JOIN syscolumns ON sysobjects.id = syscolumns.id
INNER JOIN systypes ON syscolumns.xtype = systypes.xtype
LEFT OUTER JOIN syscomments ON syscomments.id = syscolumns.cdefault
WHERE sysobjects.xtype = 'U'
AND sysobjects.name = @sTable
AND systypes.name != 'sysname'
ORDER BY
sysobjects.name,
syscolumns.colid
另一个版本如下,但它是同一个故事;在SQL Server 2005上返回一个空字符串,但在SQL Server 2008上返回正确的值。
SELECT COLUMN_DEFAULT
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_CATALOG = @sDatabase
AND TABLE_NAME = @sTable
AND COLUMN_NAME = @sColumn
这用于比较数据库之间的某些更改。最初我认为问题是因为SQL Server 2005返回默认值,如“((0))”,而SQL Server 2008返回“(0)”为相同的整数0的默认值。这就是SQL Server Management Studio分别报道。但经过进一步调查,结果表明SQL Server 2005的默认值根本就没有显示,所以它总是被记录为一个实际上没有的变化。
任何帮助深表赞赏。
谢谢!
答案 0 :(得分:4)
您是否尝试过sys.default_constraints
视图?
此代码段找到表TestTable
列nr
的默认值:
create table TestTable (nr float default 3.13)
select definition
from sys.default_constraints dc
join sys.columns c
on c.object_id = dc.parent_object_id
and c.column_id = dc.parent_column_id
where parent_object_id = object_id('TestTable')
and c.name = 'nr'