A query to get the MAX LEN of every field in a SQL table

5.5k Views Asked by At

I've been trying to come up with a query that will list the name of every column in a table with it's max length.

This is in SQL Server 2012.

Any help is greatly appreciated.

2

There are 2 best solutions below

5
Juan Carlos Oropeza On

If you want know your table detail use information_schema.columns

select * 
from information_schema.columns 
where table_name = 'YourTableName'

If you want the lenght of a string field use LEN

select len(field1)
from YourTableName
3
Anuj Tripathi On

You can use below query to get the the Actual and used length of the columns in a table

 DECLARE @TSQL VARCHAR(MAX) = ''
DECLARE @TableName sysname = 't1'
SELECT @TSQL = @TSQL + 'SELECT ' + QUOTENAME(sc.name, '''') + ' AS ColumnName, ' + QUOTENAME(t.name, '''') + ' AS DataType, ' +
QUOTENAME(sc.max_length, '''') + ' AS ActualLength, MAX(DATALENGTH(' + QUOTENAME(sc.name) + ')) AS UsedLength FROM '+@TableName+ char(10) +' UNION '
FROM sys.columns sc
        JOIN sys.types t on t.system_type_id = sc.system_type_id and t.name != 'sysname'
WHERE sc.OBJECT_ID = OBJECT_ID(@TableName)
SET @TSQL = LEFT(@TSQL, LEN(@TSQL)-6)
EXEC(@TSQL)