Last active
August 29, 2015 14:24
-
-
Save jbnv/329b02a69841aaaba8d3 to your computer and use it in GitHub Desktop.
Get the maximum value of the primary key of each table in a database. (SQL Server)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- This query generates another query which you will then run to get the maximum IDs. | |
SELECT STUFF(( | |
SELECT 'UNION SELECT '''+TABLE_SCHEMA+''' AS TABLE_SCHEMA,'''+TABLE_NAME+''' AS TABLE_NAME,'''+COLUMN_NAME+''' AS COLUMN_NAME,' | |
+'CAST(MAX(['+COLUMN_NAME+']) AS VARCHAR) FROM ['+TABLE_SCHEMA+'].['+TABLE_NAME+'] AS [MaxPrimaryKeyValue] ' | |
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE | |
WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1 | |
ORDER BY TABLE_SCHEMA,TABLE_NAME | |
FOR XML PATH('') | |
),1,6,'') + 'ORDER BY TABLE_SCHEMA,TABLE_NAME' | |
-- Example of resulting query: | |
-- SELECT 'dbo' AS TABLE_SCHEMA,'Appointments' AS TABLE_NAME,'ID' AS COLUMN_NAME,MAX([ID]) AS [MaxPrimaryKeyValue] FROM [dbo].[Appointments] | |
-- UNION SELECT 'dbo' AS TABLE_SCHEMA,'Assessments' AS TABLE_NAME,'ID' AS COLUMN_NAME,MAX([ID]) AS [MaxPrimaryKeyValue] FROM [dbo].[Assessments] | |
-- UNION SELECT 'dbo' AS TABLE_SCHEMA,'Classes' AS TABLE_NAME,'ID' AS COLUMN_NAME,MAX([ID]) AS [MaxPrimaryKeyValue] FROM [dbo].[Classes] | |
-- ORDER BY TABLE_SCHEMA,TABLE_NAME |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment