我编写了以下脚本来获取指定表的列上的一些数据:

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是该字段实际最大字符长度的两倍。我的问题是,在任何地方我都可以直接获得创建列时定义的实际最大字符长度,而无需借助这种间接计算吗?

在我看来,我用于输出数字/小数类型数据的方法也有些困惑。

谢谢

最佳答案

你有没有尝试过:

SELECT * FROM INFORMATION_SCHEMA.COLUMNS

关于sql - 替代sys.columns.max_length,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37187654/

10-10 06:47