Catalog View over Information_Schema in Microsoft SQL Server 2008

Saturday, October 24, 2009 |



Basically Catalog View was first introduced in SQL Server 2005. It provided insight view of database objects. Previously way back, we used to get this kind of insight tour via system tables, system SPs or Information_Schema view. Catalog has few advantages over others.


Many of the old System SPs and System tables are removed and Information_Schema is given in newer version also but just for the backward compatibility. It will be deprecated in future version for sure. Microsoft insists to use Catalog view over Information_Schema. You can have much better functionality in Catalog view and can do almost everything which you can do with Information_Schema. Let us look at one simple example which will show you columns of all tables or for those table which meets criteria in WHERE clause in SELECT statement.


--use of catalog view
SELECT
s.name AS schema_name,
t.name AS table_name,
t.type_desc AS table_type,
c.name AS column_name,
c.column_id,
ty.name AS data_type_name,
c.is_nullable
FROM sys.schemas s
INNER JOIN sys.tables t
ON s.schema_id = t.schema_id
INNER JOIN sys.columns c
ON t.object_id = c.object_id
INNER JOIN sys.types ty
ON c.system_type_id = ty.system_type_id
AND c.user_type_id = ty.user_type_id
where s.name='Production' and t.name='ProductReview'
GO

--use of Information_Schema
select
t.TABLE_SCHEMA as schema_name,
t.TABLE_NAME as table_name,
t.TABLE_TYPE as table_type,
c.COLUMN_NAME as column_name,
c.ORDINAL_POSITION as column_id,
c.DATA_TYPE as data_type_name,
c.IS_NULLABLE as is_nullable
from INFORMATION_SCHEMA.TABLES as t
join INFORMATION_SCHEMA.COLUMNS as c
on t.TABLE_SCHEMA=c.TABLE_SCHEMA and t.TABLE_NAME=c.TABLE_NAME
where t.TABLE_SCHEMA='Production' and t.TABLE_NAME='ProductReview'

 BTW, I have written very small note of Catalog View in past too, if you would like to read it, Click Here.


I forced myself to write this article as I still see people are so used to with Information_Schema even this is almost 5 years SQL Server 2005 introduced and even two years SQL Server 2008 is introduced (since beta). I would suggest please stop using Information_Schema and grab the power of new Catalog View.



Reference: Ritesh Shah
http://www.sqlhub.com
Note: Microsoft Books online is a default reference of all articles but examples and explanations prepared by Ritesh Shah, founder of
http://www.SQLHub.com

0 comments: