123FakeSt
IS-IT--Management
- Aug 4, 2003
- 182
I wrote this little script to change all of a schema's tables to 'dbo' but when it runs into a table that already has a 'dbo' version, it locks up my entire database until I kill the process.
Is there an easier way to acheive this?
The early bird gets the worm, but the second mouse gets the cheese.
Is there an easier way to acheive this?
Code:
DECLARE @dbusername VARCHAR(255)
DECLARE @tablename VARCHAR(255)
DECLARE @fullname VARCHAR(255)
SET @dbusername = 'notdbo'
/* Get all tables with that username */
IF OBJECT_ID('tempdb..#tables') IS NOT NULL DROP TABLE #tables
IF OBJECT_ID('tempdb..#results') IS NOT NULL DROP TABLE #results
SELECT [name] stablename INTO #tables FROM sysobjects WHERE USER_NAME(uid) = @dbusername AND xtype = 'U'
SELECT 'Step 1 - ' + stablename + ' found for user ' + @dbusername AS sresult INTO #results FROM #tables
SELECT TOP 1 @tablename = stablename FROM #tables
WHILE @@rowcount > 0
BEGIN
SET @fullname = '[' + @dbusername + '].[' + @tablename + ']'
INSERT INTO #results SELECT 'Step 2 - ' + @fullname + ' - Attempting to change to dbo'
BEGIN TRY
EXEC sp_changeobjectowner @fullname,'dbo'
END TRY
BEGIN CATCH
INSERT INTO #results SELECT 'Step 2 - ' + @fullname + ' ERROR:' + ERROR_MESSAGE()
END CATCH
DELETE FROM #tables WHERE stablename = @tablename
SELECT TOP 1 @tablename = stablename FROM #tables
END
SELECT sresult FROM #results ORDER BY 1
The early bird gets the worm, but the second mouse gets the cheese.