30.06.2013 Views

SQL Server Team-based Development - Red Gate Software

SQL Server Team-based Development - Red Gate Software

SQL Server Team-based Development - Red Gate Software

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

249<br />

Chapter 8: Exploring your Database Schema<br />

SELECT fk.name<br />

FROM sys.foreign_Key_columns fkc<br />

INNER JOIN sys.foreign_keys fk ON fkc.constraint_object_id = fk.object_id<br />

GROUP BY fk.name<br />

HAVING COUNT(*) = 1<br />

Listing 8-20: Finding composite foreign keys.<br />

This complicates the <strong>SQL</strong> that you'd use to generate these relationships, as you can see<br />

from Listing 8-21, which shows the <strong>SQL</strong> to get all the relationships for a particular table in<br />

the database, in this case, the HumanResources.Employee table.<br />

SELECT SUBSTRING(( SELECT ' AND ' + Object_Schema_name(fk.Parent_object_ID)<br />

+ '.' + OBJECT_NAME(fk.Parent_object_ID) + '.'<br />

+ cr.name + ' = '<br />

+ Object_Schema_name(fkc.referenced_object_id)<br />

+ '.' + OBJECT_NAME(fkc.referenced_object_id)<br />

+ '.' + c.NAME<br />

FROM sys.foreign_Key_columns fkc<br />

INNER JOIN sys.columns c<br />

ON fkc.referenced_column_id = c.column_id<br />

AND fkc.referenced_object_id = c.object_id<br />

INNER JOIN sys.columns cr<br />

ON fkc.parent_column_id = cr.column_id<br />

AND fkc.parent_object_id = cr.object_id<br />

WHERE fkc.constraint_object_id = fk.OBJECT_ID<br />

FOR<br />

XML PATH('')<br />

), 6, 2000) + ' – – ' + fk.name<br />

FROM sys.foreign_keys fk<br />

WHERE fk.referenced_object_ID = OBJECT_ID('HumanResources.Employee')<br />

OR fk.parent_object_id = OBJECT_ID('HumanResources.Employee')<br />

Listing 8-21: A query to find all the FK relationships for a given table.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!