Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

I've about 200 tables in SQL Server 2005 database. Almost tables has column name "AAA" which I want to set FK to column A_ID in table tbl_AAA. I want to know, how can I do this in SQL Server 2005?

share|improve this question

1 Answer 1

You can use the system view "INFORMATION_SCHEMA.COLUMNS" and build up a query which will result in the DDL statement required to carry out the task.

SELECT 
    'ALTER TABLE ' 
    + TABLE_NAME
    + ' ADD FOREIGN KEY (' 
    + COLUMN_NAME 
    + ') REFERENCES tbl_AAA(AAA);'
FROM 
    INFORMATION_SCHEMA.COLUMNS
WHERE 
    COLUMN_NAME = 'AAA' 
    AND TABLE_NAME <> 'tbl_AAA';

You can paste the output of this into SSMS and exceute it. I've done this of the top of my head so you may want to check/tweak/correct to suite your needs.

Cheers

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.