Get MSSQL Server data Schema








SELECT T.NAME AS TABLENAME
    ,C.NAME AS COLNAME
    ,DTYPE.DATA_TYPE
    ,CASE WHEN P.PK = C.NAME THEN 'PK' ELSE '' END AS ISPK
    ,DTYPE.ORDINAL_POSITION
FROM SYS.COLUMNS C
LEFT JOIN SYS.TABLES T ON C.OBJECT_ID = T.OBJECT_ID
INNER JOIN INFORMATION_SCHEMA.COLUMNS DTYPE ON T.NAME = DTYPE.TABLE_NAME
    AND C.NAME = DTYPE.COLUMN_NAME
LEFT JOIN (
    SELECT KU.TABLE_NAME AS TABLENAME
        ,KU.COLUMN_NAME AS PK
    FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC
    LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY'
        AND TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME
    WHERE KU.TABLE_NAME IS NOT NULL
    ) P ON T.NAME = P.TABLENAME
    AND C.NAME = P.PK
WHERE T.NAME = 'Customer'
ORDER BY DTYPE.ORDINAL_POSITION;

Comments

  1. Find column on the database
    Ex. Find *BOOK*

    select data.* from (
    SELECT T.NAME AS TABLENAME
    ,C.NAME AS COLNAME
    ,DTYPE.DATA_TYPE
    ,CASE WHEN P.PK = C.NAME THEN 'PK' ELSE '' END AS ISPK
    ,DTYPE.ORDINAL_POSITION
    FROM SYS.COLUMNS C
    LEFT JOIN SYS.TABLES T ON C.OBJECT_ID = T.OBJECT_ID
    INNER JOIN INFORMATION_SCHEMA.COLUMNS DTYPE ON T.NAME = DTYPE.TABLE_NAME
    AND C.NAME = DTYPE.COLUMN_NAME
    LEFT JOIN (
    SELECT KU.TABLE_NAME AS TABLENAME
    ,KU.COLUMN_NAME AS PK
    FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC
    LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY'
    AND TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME
    WHERE KU.TABLE_NAME IS NOT NULL
    ) P ON T.NAME = P.TABLENAME
    AND C.NAME = P.PK
    --WHERE T.NAME = 'Customer'
    --ORDER BY DTYPE.ORDINAL_POSITION
    ) Data
    where UPPER(Data.COLNAME) like '%BOOK%';

    ReplyDelete

Post a Comment