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.
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.
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)
Copyright © 2021 Jogjafile Inc.
If you want know your table detail use
information_schema.columnsIf you want the lenght of a string field use LEN