41

我正在使用 SQL Server 2008。我需要查找默认值约束是否不存在然后创建它。这是我尝试过的。

IF (NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME ='MyConstraint'))
BEGIN
    ALTER TABLE [XX] ADD  CONSTRAINT [MyConstraint]  DEFAULT ((-1)) FOR [XXXX]
END
GO
4

8 回答 8

59
if not exists (
    select *
      from sys.all_columns c
      join sys.tables t on t.object_id = c.object_id
      join sys.schemas s on s.schema_id = t.schema_id
      join sys.default_constraints d on c.default_object_id = d.object_id
    where t.name = 'table'
      and c.name = 'column'
      and s.name = 'schema')
  ....
于 2012-12-11T11:04:25.123 回答
30

我发现这更容易:

IF OBJECT_ID('SchemaName.MyConstraint', 'D') IS NULL
BEGIN
    -- create it here
END
于 2015-11-18T18:44:41.880 回答
8

I was a bit puzzled as to why this simple task was so complicated. In my case, I don't have constraint names - only table and column names. I want to check if they already have a default before trying to add one.

After a bit more digging, I came up with this:

IF (SELECT Column_Default FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'MY_TABLE' AND COLUMN_NAME = 'MY_COLUMN') is NULL
BEGIN
    ALTER TABLE [dbo].[MY_TABLE]
    ADD DEFAULT ('') FOR [MY_COLUMN]
END
GO

I have to implement this in a ginormous boilerplate script, so the shorter the better.

于 2019-11-06T22:43:03.127 回答
4
if not exists(select 1 from sys.default_constraints where name = 'SchemaName.MyConstraint')
begin
  -- create it here
end
于 2018-03-14T09:46:11.377 回答
0

我知道我来晚了,但我是 OBJECTPROPERTY 的忠实粉丝。如果默认值尚不存在,以下是如何在列上设置默认值 1。

IF (OBJECTPROPERTY(OBJECT_ID('My_constraint_name'),'CnstIsColumn') IS NULL
ALTER TABLE Mytable ADD  CONSTRAINT [MY_constraint_name] DEFAULT ((1)) FOR [My_column_name]
于 2021-05-27T20:07:28.117 回答
0

搜索存储数据库默认 costraints 的系统表,不带架构名称

IF EXISTS(SELECT 1 FROM sys.default_constraints WHERE [name] = 'MyConstraint')
    print 'Costraint exists!';
ELSE
    print 'Costraint doesn''t exist!';
于 2020-02-04T08:42:36.377 回答
0

我过去使用过以下内容:

DECLARE @default sysname
SELECT @default = object_name( cdefault ) FROM syscolumns WHERE id = object_id( 'DBO.TABLE' ) AND name = 'COLUMN'
IF ( not @default is null )
BEGIN
  ...
END
于 2019-05-13T14:45:31.437 回答
0

以下适用于我在 SQL Server 2016 上。

假设我有一个名为 MY_TABLE 的表和一个列 MY_COLIUMN。我想在需要添加约束的 MY_COLIUMN 上添加一个约束(默认为 '-1' )。

/* Test for the specific column */
IF EXISTS (select 1 from sys.all_columns c where c.object_id= OBJECT_ID(N'MY_TABLE') and c.name='MY_COLIUMN')
BEGIN
  /* Add default if not exits */
  IF NOT EXISTS (
      select 1 from sys.default_constraints c where c.object_id = 
      (
        select default_object_id from sys.all_columns c where c.object_id =  OBJECT_ID(N'MY_TABLE') and c.name='MY_COLIUMN'
        )
     )
  BEGIN
  ALTER TABLE MY_TABLE
    ADD DEFAULT '-1' FOR MY_COLIUMN;
  END
END
GO
于 2018-12-27T11:18:10.950 回答