Technical Article

Database, Table, Column and it's datatype

,

When reviewing a new database project to get a quick overview I used this script because I was concerned regarding the default of Varchar(max) being used inappropriately. This script showed me the extent of the issue.

/*
Database, Table, Columnn and it's datatype

Auuthor Carolyn Richardson
Date:   12/02/2023
*/

SELECT DB_Name() AS 'DATABASE',
TABLE_NAME,
COLUMN_NAME,
CASE
WHEN CHARACTER_MAXIMUM_LENGTH IS NULL AND DATA_TYPE = 'datetime2'
THEN 'datetime2'
WHEN CHARACTER_MAXIMUM_LENGTH IS NULL AND DATA_TYPE = 'datetime'
THEN 'datetime'
WHEN CHARACTER_MAXIMUM_LENGTH IS NULL AND DATA_TYPE = 'int'
THEN 'int'
WHEN CHARACTER_MAXIMUM_LENGTH IS NULL AND DATA_TYPE = 'bigint'
THEN 'bigint'
WHEN CHARACTER_MAXIMUM_LENGTH IS NULL AND DATA_TYPE = 'bit'
THEN 'bit'
WHEN CHARACTER_MAXIMUM_LENGTH IS NULL AND DATA_TYPE = 'float'
THEN 'float'
WHEN CHARACTER_MAXIMUM_LENGTH IS NULL AND DATA_TYPE = 'uniqueidentifier'
THEN 'uniqueidentifier'
WHEN CHARACTER_MAXIMUM_LENGTH IS NULL AND DATA_TYPE = 'decimal'
THEN 'decimal('+CAST(NUMERIC_PRECISION AS VARCHAR(5))+ ',' +CAST(NUMERIC_SCALE AS VARCHAR(50))+')'
WHEN Cast(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(5)) = - 1 AND DATA_TYPE = 'nvarchar'
THEN 'nvarchar(Max)'
WHEN Cast(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(5)) = - 1 AND DATA_TYPE = 'varchar'
THEN 'varchar(Max)'
WHEN DATA_TYPE = 'nvarchar' AND Cast(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(5)) <> -1
THEN  '(nvarchar' + Cast(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(5)) + ')'
WHEN DATA_TYPE = 'nvarchar' AND Cast(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(5)) <> -1
THEN  '(varchar' + Cast(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(5)) + ')'
ELSE 'unknown'
END AS [Type]
FROM INFORMATION_SCHEMA.COLUMNS

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating