I need to create a script to check if a table has primary key
, if it does not, it is added to primary key
.
I found this form to do the script, I did not understand where it takes the name of this table "INFORMATION_SCHEMA.TABLE_CONSTRAINTS"
, and in where "CONSTRAINT_TYPE"
and "TABLE_SCHEMA"
.
I'm starting to learn how to tweak SQL, if anyone can heal my doubt thank you.
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = 'Persons'
AND TABLE_SCHEMA ='dbo')
BEGIN
ALTER TABLE Persons ADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id)
END