Search code examples
sql-servert-sqlsql-server-2008sysobjects

Getting Table Information


I am trying to get the table information give a table name so I wrote a query like this:

 SELECT so.name, sc.name, st.name, sc.length, CASE WHEN sc.status = 0x80 THEN 'Y' ELSE 'N' END AS IsIdent, ColOrder
   FROM Asdim.dbo.sysobjects so
   INNER JOIN Asdim.dbo.syscolumns sc
   ON so.id=  sc.id
   INNER JOIN Asdim.dbo.systypes st
   ON sc.xtype = st.xusertype
   WHERE so.Name = 'Admin'

The problem is that I have two tables with name 'Admin' but they have different schemas. So when I run this query:

SELECT * FROM Asdim.dbo.sysobjects WHERE name LIKE 'Admin'

I get two records since the table names are same. Is there a way that I caould filter out based on the schema name too?


Solution

  • The views you are using are all deprecated and just supplied for backward compatibility. Using the new views gives.

    SELECT t.name,
           c.name,
           ty.name,
           c.is_identity,
           c.max_length,
           c.column_id
    FROM sys.tables t
    JOIN sys.schemas s ON s.schema_id=t.schema_id
    JOIN sys.columns c ON c.object_id = t.object_id
    JOIN sys.types ty ON ty.user_type_id = c.user_type_id
    WHERE t.name LIKE '%Admin%' AND s.name = 'dbo'
    

    INFORMATION_SCHEMA.COLUMNS has nearly all the information you need but is missing info about identity columns.