我编写了以下脚本来获取指定表的列的一些数据:
DECLARE @QueryTable varchar(35);
SET @QueryTable = 'Test';
SELECT DISTINCT
sys.columns.name AS 'Column',
sys.types.name AS 'Data type',
CASE WHEN sys.types.name IN ('varchar', 'char') THEN CAST(sys.columns.max_length AS varchar(5))
WHEN sys.types.name IN ('decimal', 'numeric') THEN CAST(CAST (sys.columns.precision AS nvarchar(10)) + ', ' + CAST(sys.columns.scale AS nvarchar(10)) AS nvarchar(10))
WHEN sys.types.name IN ('nvarchar', 'nchar') THEN CAST(sys.columns.max_length / 2 AS varchar(5))
ELSE '-' END AS 'Max size',
CASE WHEN sys.columns.is_nullable = 1 THEN 'YES'
WHEN sys.columns.is_nullable = 0 THEN 'NO' END AS 'Allow nulls',
CASE WHEN sys.columns.name IN (SELECT Col.COLUMN_NAME from
INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab,
INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col
WHERE
Col.Constraint_Name = Tab.CONSTRAINT_NAME
AND Col.Table_Name = Tab.TABLE_NAME
AND Constraint_Type = 'PRIMARY KEY'
AND Col.Table_Name = @QueryTable) THEN 'PK'
ELSE '' END AS 'Primary Key'
FROM
sys.columns, sys.types, sys.tables
WHERE
sys.tables.object_id = sys.columns.object_id AND
sys.types.system_type_id = sys.columns.system_type_id AND
sys.types.user_type_id = sys.columns.user_type_id AND
sys.tables.name = @QueryTable
ORDER BY sys.columns.name
当然,对于 nvarchar 和 nchar 类型,我得到的max_length是该字段实际最大字符长度的两倍。我的问题是,我是否可以直接获得创建列时定义的实际最大字符长度,而无需借助此间接计算?
我用来输出数字/小数类型数据的方法在我看来也是一种混乱。
谢谢
答案 0 :(得分:4)
你试过了吗?
SELECT * FROM INFORMATION_SCHEMA.COLUMNS