Menu Bar

Tuesday, September 13, 2011

So what do my tables look like anyway (Part 2)

I'm a doctor, not an engineer." - Doctor Leonard McCoy, Star Trek, The Original Series

I've used the script from the last entry on and off over the years and have not yet had the need to do this in SQL Server.

I started trying to write my own code to perform the same task and thought to do a Google search and found the following:

So, I'm replicating that code here, just so should I ever need it, I'll have it at my fingertips.

The one thing that this does that my Oracle variant does not, is list constraints as well.

  obj.NAME AS TableName
 ,col.NAME AS ColumnName
 ,sys.systypes.NAME + 
       WHEN systypes.NAME LIKE 'n%char' 
         THEN ' (' + CONVERT(NVARCHAR, col.length / 2) + ')' 
       WHEN systypes.NAME LIKE '%char%' 
         THEN ' (' + CONVERT(NVARCHAR, col.length) + ')' 
       ELSE '' 
     END AS DataType
 ,CASE col.isnullable 
    WHEN 0 
      THEN 'NOT NULL' 
    ELSE '' 
      END AS Nullable
    WHEN COLUMNPROPERTY(, col.NAME, 'IsIdentity') = 1 
    WHEN conobj.type = 'D' 
      THEN 'DEFAULT ' + syscomments.TEXT 
    WHEN conobj.type = 'F' 
      THEN 'REFERENCES ' + fkobj.NAME + '.' + fkcol.NAME 
    ELSE '' 
      END AS Constraints
FROM       sys.sysobjects AS obj
INNER JOIN sys.syscolumns AS col 
        ON =
INNER JOIN sys.systypes 
        ON sys.systypes.xtype = col.xtype
LEFT JOIN  sys.sysconstraints AS con
INNER JOIN sys.sysobjects AS conobj 
        ON con.constid = 
        ON = AND con.colid = col.colid
LEFT JOIN  sys.syscomments ON =
LEFT JOIN  sys.sysforeignkeys AS fk
INNER JOIN sys.syscolumns AS fkcol 
        ON fk.rkeyid = AND fk.rkey = fkcol.colid
INNER JOIN sys.sysobjects AS fkobj 
        ON = 
        ON = fk.constid 
       AND = fk.fkeyid 
       AND col.colid = fk.fkey
WHERE (obj.type = 'U') AND (sys.systypes.NAME <> 'sysname')
ORDER BY obj.NAME, col.colid

No comments:

Post a Comment