Skip to content

Instantly share code, notes, and snippets.

@kdarty
Created October 8, 2015 18:02
Show Gist options
  • Save kdarty/081c2ac828a1a083f6e2 to your computer and use it in GitHub Desktop.
Save kdarty/081c2ac828a1a083f6e2 to your computer and use it in GitHub Desktop.
If you are ever in a position where you need to migrate data from one SQL Server Database (or Table) to Another which differ in Column sizes (length of fields), use this script to determine the Max Length of each column to compare for your Migration Scripts. Once you know the Max Length of the Data you are getting, you can properly handle placin…
--Source Discussion: https://community.spiceworks.com/topic/131997-sql-copy-field-in-to-smaller-field
--Author: Jason Crider - https://twitter.com/jasoncrider
--Get MaxLength on all columns in a table
DECLARE @SQL VARCHAR(MAX)
DECLARE @TableName sysname
SET @TableName = 'INSERT_TABLENAME_HERE'
SET @SQL = ''
SELECT @SQL = @SQL + 'SELECT ' + QUOTENAME(sc.name, '''') + ' AS ColumnName, ' + QUOTENAME(t.name, '''') + ' AS DataType, ' +
QUOTENAME(sc.max_length, '''') + ' AS SetLength, MAX(DATALENGTH(' + QUOTENAME(sc.name) + ')) AS MaxLength 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 @SQL = LEFT(@SQL, LEN(@SQL)-6)
PRINT @SQL
EXEC(@SQL)
--Truncate and Trim the Data to fit new Column
--NOTE: Before doing this you should run the above script to see if you need to increase Column Size
SELECT RTRIM(LTRIM(LEFT(FirstName, 50))) AS [FirstName]
FROM OldDatabase.dbo.OldTable;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment