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..

Matthew Abbott
  • 60,571
  • 9
  • 104
  • 129
Leema
  • 97
  • 3
  • 13

1 Answers1

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.

Jeen Broekstra
  • 21,642
  • 4
  • 51
  • 73