How do I return the SQL data types from my query?

前端 未结 13 1495
耶瑟儿~
耶瑟儿~ 2021-01-29 23:58

I\'ve a SQL query that queries an enormous (as in, hundreds of views/tables with hard-to-read names like CMM-CPP-FAP-ADD) database that I don\'t need nor want to understand. Th

13条回答
  •  余生分开走
    2021-01-30 00:24

    I use a simple case statement to render results I can use in technical specification documents. This example does not contain every condition you will run into with a database, but it gives you a good template to work with.

    SELECT
         TABLE_NAME          AS 'Table Name',
         COLUMN_NAME         AS 'Column Name',
         CASE WHEN DATA_TYPE LIKE '%char'
              THEN DATA_TYPE + '(' + CONVERT(VARCHAR, CHARACTER_MAXIMUM_LENGTH) + ')'
              WHEN DATA_TYPE IN ('bit', 'int', 'smallint', 'date')
              THEN DATA_TYPE
              WHEN DATA_TYPE = 'datetime'
              THEN DATA_TYPE + '(' + CONVERT(VARCHAR, DATETIME_PRECISION) + ')'
              WHEN DATA_TYPE = 'float'
              THEN DATA_TYPE
              WHEN DATA_TYPE IN ('numeric', 'money')
              THEN DATA_TYPE + '(' + CONVERT(VARCHAR, NUMERIC_PRECISION) + ', ' + CONVERT(VARCHAR, NUMERIC_PRECISION_RADIX) + ')'
         END                 AS 'Data Type',
         CASE WHEN IS_NULLABLE = 'NO'
              THEN 'NOT NULL'
              ELSE 'NULL'
         END                 AS 'PK/LK/NOT NULL'
    FROM INFORMATION_SCHEMA.COLUMNS 
    ORDER BY 
         TABLE_NAME, ORDINAL_POSITION
    

提交回复
热议问题