Anatoly Lubarsky Logo
MSSQL, .NET, Design. Life and Music

MSSQL: Change tables owner to dbo with sp_changeobjectowner

Sometimes there is a need to change all tables in the database to be owned by dbo for maintenance or to fix up accidental errors. All tables owned by dbo schema is usually best practices in the database application development with MSSQL while we can meet different approaches in real life...


The following small SQL code snippet goes through all user tables in the database and changes their owner to dbo. It uses sp_changeobjectowner system stored procedure:


DECLARE tabcurs CURSOR
FOR
    SELECT 'SOMEOWNER.' + [name]
      FROM sysobjects
     WHERE xtype = 'u'

OPEN tabcurs
DECLARE @tname NVARCHAR(517)
FETCH NEXT FROM tabcurs INTO @tname

WHILE @@fetch_status = 0
BEGIN

    EXEC sp_changeobjectowner @tname, 'dbo'

    FETCH NEXT FROM tabcurs INTO @tname
END
CLOSE tabcurs
DEALLOCATE tabcurs

Related Posts:

Friday, December 05, 2003 5:40 PM

Comments

# re: MSSQL: Change tables owner to dbo wi
Thanks so much for this, was trying to find a way to overcome this exact issue.

3/12/2007 12:09 AM by mcm

# re: MSSQL: Change tables owner to dbo wi
This worked perfectly! Needed it for stored procedures, so I just changed the xtype. Thanks!

3/19/2007 8:00 PM by mkt

If your feedback doesn't appear right away, please be patient as it may take a few minutes to publish.

Post a Comment

Protected by CAPTCHAEnter the code you see
Name (*)  
E-mail (*)  
Url
Remember

Comment (*)