SET NOCOUNT ON
/* Set the new owner name here in place of the ‘dbo’ user */
DECLARE @New_Owner_Name Sysname
SET @New_Owner_Name = 'dbo'
DECLARE @Object_ID Int, @Object_Name Sysname, @Owner_ID Int, @Owner_Name Sysname, @Owner_Object_Name Sysname
DECLARE CUR_ReplaceObjectOwner CURSOR FOR
/* Run this select query by itself to see the set of user objects you are working with */
SELECT so.id AS ObjectID, so.name AS ObjectName, so.uid AS OwnerID, su.name AS OwnerName, '[' + su.name + '].' + '[' + so.name + ']' AS OwnerObjectName
FROM sysobjects so, sysusers su
WHERE so.uid = su.uid
AND so.xtype IN ('U','P','FN','V')
AND so.name NOT LIKE '%dt_;%'
AND so.name NOT IN ('syssegments', 'sysconstraints')
ORDER BY xtype
/* Get the results from the query and load the first row into the cursor */
OPEN CUR_ReplaceObjectOwner
FETCH NEXT FROM CUR_ReplaceObjectOwner
INTO @Object_ID, @Object_Name, @Owner_ID, @Owner_Name, @Owner_Object_Name
WHILE @@FETCH_STATUS = 0
BEGIN
IF @New_Owner_Name != @Owner_Name
/* Make the object owner change here */
EXEC sp_changeobjectowner @Owner_Object_Name, @New_Owner_Name
/* Load the next row into the cursor */
FETCH NEXT FROM CUR_ReplaceObjectOwner
INTO @Object_ID, @Object_Name, @Owner_ID, @Owner_Name, @Owner_Object_Name
END
/* Clean up */
CLOSE CUR_ReplaceObjectOwner
DEALLOCATE CUR_ReplaceObjectOwner
SET NOCOUNT OFF
GO