3
I need to create a script to check if a table has primary key
, if not, is added to primary key
.
I found this way to make the script, nas did not understand where it takes the name of this table "INFORMATION_SCHEMA.TABLE_CONSTRAINTS"
, and in the where "CONSTRAINT_TYPE"
and "TABLE_SCHEMA"
.
I’m starting to learn how to handle SQL, if anyone can remedy my question I thank.
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
the script may even work and you can use it as a didactic form, but there is no real application for it. Primary keys are not created in the second moment, at runtime, but in development time.
– Thiago Lunardi
I don’t know what to make of that question. I even found the doubt interesting, as a technical curiosity, but it gives me a certain cold in the belly to imagine where it would be used in practice.
– Bacco
Bacco, probably this table is only used to load a drop, which made table not bothered to put Primary key thinking it would only be used in the drop, the more the system grows and there is a need to create the Primary key to link with another table.
– krispim