我正在尝试测试是否存在给定的默认约束.我不想使用sysobjects表,但更标准的INFORMATION_SCHEMA.
我之前用它来检查表和主键约束,但我没有看到任何地方的默认约束.
他们不在吗?(我正在使用MS SQL Server 2000).
编辑:我希望得到约束的名称.
据我了解,默认值约束不是ISO标准的一部分,因此它们不会出现在INFORMATION_SCHEMA中.INFORMATION_SCHEMA似乎是此类任务的最佳选择,因为它是跨平台的,但如果信息不可用,则应使用对象目录视图(sys.*)而不是SQL Server中不推荐使用的系统表视图2005年及以后.
以下几乎与@ user186476的答案相同.它返回给定列的默认值约束的名称.(对于非SQL Server用户,您需要默认名称才能删除它,如果您没有自己命名默认约束,SQL Server会创建一些疯狂的名称,如"DF_TableN_Colum_95AFE4B5".更容易更改将来你的架构,总是明确命名你的约束!)
-- returns name of a column's default value constraint SELECT default_constraints.name FROM sys.all_columns INNER JOIN sys.tables ON all_columns.object_id = tables.object_id INNER JOIN sys.schemas ON tables.schema_id = schemas.schema_id INNER JOIN sys.default_constraints ON all_columns.default_object_id = default_constraints.object_id WHERE schemas.name = 'dbo' AND tables.name = 'tablename' AND all_columns.name = 'columnname'
通过指定默认约束与之关联的表名和列名,可以使用以下内容进一步缩小结果范围:
select * from sysobjects o inner join syscolumns c on o.id = c.cdefault inner join sysobjects t on c.id = t.id where o.xtype = 'D' and c.name = 'Column_Name' and t.name = 'Table_Name'
Information_Schema
视图中似乎没有默认约束名称.
用于SELECT * FROM sysobjects WHERE xtype = 'D' AND name = @name
按名称查找默认约束
下面的脚本列出了所有默认约束以及运行它的数据库中用户表的默认值:
SELECT b.name AS TABLE_NAME, d.name AS COLUMN_NAME, a.name AS CONSTRAINT_NAME, c.text AS DEFAULT_VALUE FROM sys.sysobjects a INNER JOIN (SELECT name, id FROM sys.sysobjects WHERE xtype = 'U') b on (a.parent_obj = b.id) INNER JOIN sys.syscomments c ON (a.id = c.id) INNER JOIN sys.syscolumns d ON (d.cdefault = a.id) WHERE a.xtype = 'D' ORDER BY b.name, a.name
If you want to get a constraint by the column or table names, or you want to get all the constraints in the database, look to other answers. However, if you're just looking for exactly what the question asks, namely, to "test if a given default constraint exists ... by the name of the constraint", then there's a much easier way.
Here's a future-proof answer that doesn't use the sysobjects
or other sys
tables at all:
IF object_id('DF_CONSTRAINT_NAME', 'D') IS NOT NULL BEGIN -- constraint exists, work with it. END