2014-12-08 72 views
1

我需要比較定義的長度和SQL中的實際值。動態獲取每列的最大長度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基於元數據的輸出。

+0

我使用的SQL Server。 – MMakati 2014-12-08 08:08:23

回答

3

試試這個:

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; 
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'