Sunday, April 3, 2011

Check for constraint on table

If I check for a column's existance as follows, before adding it, how would I do the equivalent for a UNIQUE constraint?

IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id=OBJECT_ID('[Table]') AND [Name]='Column')
    ALTER TABLE [Table] 
    ADD 
    [Column] varchar(500)
From stackoverflow
  • Something like this for a constraint FK_myTable (SQL 2000):

    if not exists ( select *
        from sysconstraints sc
        inner join sysobjects tbl on sc.id = tbl.id
        inner join sysobjects con on sc.constid = con.id
        where tbl.name = 'myTable' and con.name = 'FK_myTable' )
    
    jhale : I believe that sysconstraints and sysobjects have been deprecated and you are no longer supposed to use them.
    MikeW : I'm still living in a cave and using SQL 2000 :)
  • select * from sys.objects where type = 'uq' and parent_object_id = OBJECT_ID('[Table]')

0 comments:

Post a Comment