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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 8: Exploring your Database Schema<br />

- – you can save a lot of code by using the catalog views<br />

- – along with the OBJECTPROPERTY() function<br />

SELECT DB_NAME() + '.' + object_schema_name(t.object_ID) + '.' + t.name<br />

AS [tables without primary keys]<br />

FROM sys.tables t<br />

WHERE OBJECTPROPERTY(object_id, 'TableHasPrimaryKey') = 0<br />

AND OBJECTPROPERTY(object_id, 'IsUserTable') = 1<br />

ORDER BY [tables without primary keys]<br />

Listing 8-4: Finding tables with no primary key using a Catalog view.<br />

Tables with no referential constraints<br />

You can, of course, use almost the same query to explore many other characteristics of<br />

the tables. You'd certainly want to investigate any tables that seem to have no referential<br />

constraints, either as a key or a foreign reference, as shown in Listing 8-5.<br />

--Which of my table are waifs? (No referential constraints)<br />

SELECT<br />

DB_NAME() + '.' + object_schema_name(t.object_ID)<br />

+ '.' + t.name AS [Waif Tables]<br />

FROM sys.tables t<br />

WHERE OBJECTPROPERTY(object_id, 'TableHasForeignKey') = 0<br />

AND OBJECTPROPERTY(object_id, 'TableHasForeignRef') = 0<br />

AND OBJECTPROPERTY(object_id, 'IsUserTable') = 1<br />

ORDER BY [Waif tables]<br />

Listing 8-5: Finding waif tables.<br />

232

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

Saved successfully!

Ooh no, something went wrong!