动态获取每列的最大长度SQL

时间:2014-12-08 07:12:49

标签: sql sql-server metadata

我需要比较定义的长度和SQL中的实际值。

例如:

+--------------|---------------------|-------------+
  COLUMN_NAME  | DefinitionMaxLength |ActualLength
+--------------|---------------------|-------------+
 COL 1         | 20                  | 25
 COL 2         | 30                  | 26

这是我获取表格元数据的SQL。

SELECT COLUMN_NAME, CHARACTER_MAXIMUM_LENGTH AS DefinitionMaxLength  
from INFORMATION_SCHEMA.COLUMNS as COL  
WHERE COL.DATA_TYPE ='varchar' AND COL.TABLE_NAME='TableSRC'

我现在的问题是如何获得实际表的最大长度。我使用Max(Len(COLUMN_NAME)),但这不起作用。

SELECT  TABLE_NAME, COLUMN_NAME, CHARACTER_MAXIMUM_LENGTH AS DefinitionMaxLength, MAX(LEN(COLUMN_NAME))  
from INFORMATION_SCHEMA.COLUMNS as COL  
WHERE COL.DATA_TYPE ='varchar' AND COL.TABLE_NAME='TableSRC'

COLUMN_NAME基于元数据的输出。

2 个答案:

答案 0 :(得分:4)

试试这个:

SELECT COLUMN_NAME, CHARACTER_MAXIMUM_LENGTH AS DefinitionMaxLength
, N'SELECT @resultOUT = MAX(LEN(' + COLUMN_NAME + ')) FROM ' + COL.TABLE_NAME [query]
, ORDINAL_POSITION
, 0 [ActualMaxLength]
INTO #tmp
FROM INFORMATION_SCHEMA.COLUMNS as COL 
WHERE COL.DATA_TYPE ='varchar' AND COL.TABLE_NAME='TableSRC';

DECLARE
    @pos int = (SELECT MIN(ORDINAL_POSITION) FROM #tmp),
    @result int,
    @query NVARCHAR(MAX) = N'',
    @param_def NVARCHAR(100) = N'@resultOUT int OUTPUT';

WHILE EXISTS (SELECT * FROM #tmp WHERE ORDINAL_POSITION > @pos)
BEGIN
    SELECT @query = [query] FROM #tmp WHERE ORDINAL_POSITION = @pos;
    EXECUTE sp_executesql @query, @param_def, @resultOUT = @result OUTPUT;

    UPDATE #tmp SET [ActualMaxLength] = ISNULL(@result, 0) WHERE ORDINAL_POSITION = @pos;

    SET @pos = (SELECT MIN(ORDINAL_POSITION) FROM #tmp WHERE ORDINAL_POSITION > @pos);
END

SELECT COLUMN_NAME, DefinitionMaxLength, ActualMaxLength FROM #tmp;

DROP TABLE #tmp;

答案 1 :(得分:0)

在cte中进行聚合并加入information_schema。

with data_length(column_name,  actual_max_length) as
(
select 'col1', max(len(col1))
from t
union all 
select 'col2', max(len(col2))
from t
)

select c.column_name, c.character_maximum_length,    d.actual_max_length
from information_schema.columns c
join data_length do
on d.column_name = c.column_name
where c.table_name = 't'