declare @new_name varchar(max), @query varchar(max)
IF OBJECT_ID('tempdb..#temp') IS NOT NULL DROP TABLE #temp
;WITH TableRows AS
(
SELECT
SUM(row_count) AS [RowCount],
OBJECT_NAME(OBJECT_ID) AS TableName
FROM
sys.dm_db_partition_stats
WHERE
(index_id = 0 OR index_id = 1)
and (LEFT(OBJECT_NAME(OBJECT_ID), 3) <> 'sys')
GROUP BY
OBJECT_ID
)
SELECT * into #temp
FROM TableRows
WHERE [RowCount] = 0
order by TableName
DECLARE db_cursor CURSOR FOR
SELECT tablename
FROM #temp
OPEN
db_cursor
declare @name varchar(max)
FETCH
NEXT FROM db_cursor INTO @name
WHILE (@@FETCH_STATUS = 0)
BEGIN
set @new_name = @name + '__EMPTY'
set @query = 'exec sp_rename ''' + @name + ''',''' + @new_name + ''''
exec(@query)
FETCH NEXT FROM db_cursor INTO @name
END
CLOSE db_cursor
deallocate db_cursor
IF OBJECT_ID('tempdb..#temp') IS NOT NULL DROP TABLE #temp
I used the technique described in this Stack Overflow post to find the empty tables.
Web application R&D notes, from the world of Java, Flex, CSS, XHTML, Flash, .NET, cross-browser compatibility, JavaScript, AJAX, ADA compliance, Photoshop, and any and all things related to Web development!
11 February 2016
Rename all empty SQL Server tables
I'm working on a large database on the developer server and need a way to sift through and analyze the data. This is for a project where we're going to discard these tables and build a new system; in the meantime, I need to work with the copy of the old data. To that end, I created this T-SQL script to append all empty tables' names with '__EMPTY'.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment