how to check and alter constraints

1

hi can anyone tel me how to check whether a primary key exists or not in a table and add a primary key if not exixts in sql server compact(.sdf)..

i'm using this,

  IF NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE = 'PRIMARY KEY') 
   BEGIN 
       alter table [tablename] add constraint [name] PRIMARY KEY (columnname)
   END

when i execute this in sql server compact i get this error..

Major Error 0x80040E14, Minor Error 25501

IF NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE = 'PRIMARY KEY') BEGIN alter table [tablename] add constraint [name] PRIMARY KEY (columnname) END There was an error parsing the query. [ Token line number = 1,Token line offset = 1,Token in error = IF ]

thank you..

sql
constraints
key
alter
compact-database
asked on Stack Overflow Aug 28, 2010 by Leema • edited Aug 28, 2010 by Matthew Abbott

1 Answer

0
 IF NOT EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'PRIMARY KEY') AND type in (N'U') )
   BEGIN 
       alter table [tablename] add constraint [PRIMARY KEY] PRIMARY KEY CLUSTERED (columnname)
   END

Please use the above query and let me know if it works. thanks.

answered on Stack Overflow Jun 4, 2015 by Mahesh Kumar • edited Jun 4, 2015 by Jeen Broekstra

User contributions licensed under CC BY-SA 3.0