Skip to content

Instantly share code, notes, and snippets.

@dtheodor
Created October 9, 2022 07:42
Show Gist options
  • Save dtheodor/bc756c1a2a5a971f08c7ccb5706b44d6 to your computer and use it in GitHub Desktop.
Save dtheodor/bc756c1a2a5a971f08c7ccb5706b44d6 to your computer and use it in GitHub Desktop.
Profile table varchar lengths T-SQL
CREATE PROCEDURE profile_table_varchar_lengths @table nvarchar(256)
AS BEGIN
IF OBJECT_ID(@table, 'U') IS NULL
RAISERROR ('Table %s does not exist', 16, 1, @table) WITH NOWAIT;
DECLARE @sql nvarchar(max);
with varchar_cols as (
SELECT c.name, t.name as type, c.max_length
from sys.columns c
join sys.types t on t.system_type_id = c.system_type_id
where c.object_id = object_id(@table)
AND t.name IN ('varchar', 'nvarchar')
)
SELECT @sql = string_agg(cast(
'SELECT ''' + name + ''' as name, ' +
'''' + type + ''' as type, ' +
'CAST(''' + CAST(max_length as nvarchar(128)) + ''' as int) as declared_max_length, ' +
'max(len(' + name + ')) as max_length ' +
'FROM ' + @table
as nvarchar(max)), ' UNION ALL ') + ' ORDER BY 1'
from varchar_cols
;
EXEC sp_executesql @sql;
END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment