Click here to Skip to main content
15,898,373 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
As per my requirement i had created a table of name Users with columns (Userid,Usename,Password,Createddate,lastlogindate) for the first column ie User id i haven't applied any constraint...but after creating table i need to apply PRIMARY KEY for the column Userid for that i need not want to alter the table [Users]..What the thing i did is ..i want to check the table for constraints, if there is no constraints on my column, the query must set the constraint.. and if there exists the constraints the query must do nothing just printing already query exists

the query which i had wrote is
SQL
if not Exists(select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
    where CONSTRAINT_TYPE='PRIMARY KEY' AND TABLE_NAME='Users' and TABLE_SCHEMA='dbo')
    begin
    alter table Users add constraint Pk_Userid Primary key(Userid)
    end
    else
    begin
       --key exists
    end

but at the end of query at the '
end
' statement it was throwing an error
How to make my mistake in a right path of execution.....
Posted

1 solution

run this:

SQL
if not Exists(select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
    where CONSTRAINT_TYPE='PRIMARY KEY' AND TABLE_NAME='Users' and TABLE_SCHEMA='dbo')
    alter table Users add constraint Pk_Userid Primary key(Userid)
    else
       print 'key exists'
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900