>>>>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
>>>
>>>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
>>>
>>>ORDER BY
>>> 1,2,3,4
>>
>>I am looking at your code and it does show the list of FK constraints (I am learning a lot from these examples). But how do I actually display to the Query window the FK scripts?
>>
>>Another approach I found that could possible do what I am looking to do is to right-mouse click on the Database and then go to Tasks -> Generate Scripts. But then I need to create only the Foreign Key constraints. And on the Choose Script Options it looks like I can disable (False) all but the Script Foreign Keys option. But I have not done it since I don't know if these options will change permanently in the SQL Server. And next time I might need to script all options.
>
>The blog link I gave you does 'ALTER TABLE' script to drop / add constraints.
>
>Alternatively, you should be able to do it with the PowerShell script. You may want to google on 'PowerShell foreign constraints script'
Thank you. I will follow your suggestion.
"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