获取所有列中的最大条目长度

时间:2014-12-15 14:24:20

标签: sql-server

我发现了一个类似的条目,只是寻找varchar列的长度。提供的答案是:

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 :(得分:0)

这是你正在寻找的吗? (如果我已经给你答案而且它不是你想要的,请用一些数据样本更新问题。)

注意:生成的查询可能非常慢。你已被警告过了。

DECLARE @Tsql NVARCHAR(MAX)
SET @Tsql = ''

SELECT @Tsql = @Tsql + 'SELECT ''' + c.TABLE_SCHEMA + ''' AS TABLE_SCHEMA, ' +
    '''' + c.TABLE_NAME + ''' AS TABLE_NAME, ' +
    '''' + CAST(c.CHARACTER_MAXIMUM_LENGTH AS VARCHAR) + ''' AS CHARACTER_MAXIMUM_LENGTH, ' +
    'MAX(LEN([' + c.COLUMN_NAME + '])) AS MaxDataLength ' +
    'FROM [' + c.TABLE_SCHEMA + '].[' + c.TABLE_NAME + '] UNION' + CHAR(13) + CHAR(10)
FROM INFORMATION_SCHEMA.COLUMNS c
JOIN INFORMATION_SCHEMA.TABLES t
    ON t.TABLE_SCHEMA = c.TABLE_SCHEMA
    AND t.TABLE_NAME = c.TABLE_NAME

--Include/exclude views as desired
WHERE t.TABLE_TYPE IN ('BASE TABLE', 'VIEW')

--Include/exclude nvarchar data type as desired
AND c.DATA_TYPE IN ('nvarchar', 'varchar')

--Trim off the last UNION
SET @Tsql = RTRIM(@Tsql)
SET @Tsql = LEFT(@Tsql, LEN(@Tsql) - 7)

PRINT @Tsql
--Uncomment when ready to proceed
--EXEC (@Tsql)