Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Script for all FK Constraints in a Database?
Message
 
 
Information générale
Forum:
Microsoft SQL Server
Catégorie:
Autre
Versions des environnements
SQL Server:
SQL Server 2008
Divers
Thread ID:
01537261
Message ID:
01537270
Vues:
16
>>>>Hi,
>>>>
>>>>Is there a way to create a script of all FK Constraints in a database such that I could apply this script to anther database? or the same database after some or all of the constraints are deleted?
>>>>
>>>>TIA.
>>>
>>>
>>>SELECT 
>>> OBJECT_NAME(f.rkeyid) PK_Table_name,
>>> c2.name PK_Column_name,
>>> OBJECT_NAME(f.constid) Constraint_name,
>>> OBJECT_NAME(f.fkeyid) FK_Table_name,
>>> c1.name FK_Column_name
>>>FROM dbo.sysforeignkeys f
>>>INNER JOIN dbo.syscolumns c1 ON c1.id = f.fkeyid AND c1.colid = f.fkey
>>>INNER JOIN dbo.syscolumns c2 ON c2.id = f.rkeyid AND c2.colid = f.rkey
>>>--where Object_Name(fkeyId) = 'Foreign Table Name' 
>>>ORDER BY PK_Table_name, FK_Table_name, FK_Column_name;
>>>
>>>Alternatively
>>>
>>>SELECT 
>>>    PK_Table  = PK.TABLE_NAME,    
>>>    PK_Column = PT.COLUMN_NAME, 
>>>    FK_Table  = FK.TABLE_NAME, 
>>>    FK_Column = CU.COLUMN_NAME, 
>>> 
>>>    Constraint_Name = C.CONSTRAINT_NAME 
>>>FROM 
>>>    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C 
>>>    INNER JOIN 
>>>    INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK 
>>>        ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME 
>>>    INNER JOIN 
>>>    INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK 
>>>        ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME 
>>>    INNER JOIN 
>>>    INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU 
>>>        ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME 
>>>    INNER JOIN 
>>>    ( 
>>>        SELECT 
>>>            i1.TABLE_NAME, i2.COLUMN_NAME 
>>>        FROM 
>>>            INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1 
>>>            INNER JOIN 
>>>            INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 
>>>            ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME 
>>>            WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY' 
>>>    ) PT 
>>>    ON PT.TABLE_NAME = PK.TABLE_NAME 
>>>-- optional: 
>>>ORDER BY 
>>>    1,2,3,4
>>
>>Thank you.
>
>You're welcome. I have My Projects folder organized. In particular, I have Meta-Data folder there. So, I just took two scripts I already have saved.

I want to be organized too. When I grow up I want to be like you :)
"The creative process is nothing but a series of crises." Isaac Bashevis Singer
"My experience is that as soon as people are old enough to know better, they don't know anything at all." Oscar Wilde
"If a nation values anything more than freedom, it will lose its freedom; and the irony of it is that if it is comfort or money that it values more, it will lose that too." W.Somerset Maugham
Précédent
Répondre
Fil
Voir

Click here to load this message in the networking platform