Home Forums SQL Server 7,2000 Administration Problems accessing SQL Server when NT account has been renamed RE: Problems accessing SQL Server when NT account has been renamed

  • Stephen,

    The script below can also be modified to suit your needs. It should crawl all database objects and report on ownership for you. Thanks to Scott Coleman for being the original poster of the code with SQL 2000 and SQL 2005 syntax.

    -- Author: Scott Coleman

    -- Date: 15-JAN-2008

    --Source: http://www.sqlservercentral.com/Forums/Topic413580-359-1.aspx

    --

    -- SQL 2000

    -- In SQL 2000 the owner or schema of an object was indicated by the

    -- uid value in sysobjects and could be looked up in sysusers.

    SELECT o.xtype, QUOTENAME(u.name) + '.' + QUOTENAME(o.name) AS Object, u.name AS Owner

    FROM sysobjects AS o

    INNER JOIN sysusers AS u ON u.uid = o.uid

    WHERE ( u.name = 'dbo' )

    -- SQL 2005

    -- In SQL 2005 the owner of an object may be indicated by principal_id (links

    -- to sys.database_principals), but if this is null then ownership defaults

    -- to the schema_id (links to sys.schemas).

    SELECT o.type_desc, QUOTENAME(s.name) + '.' + QUOTENAME(o.name) AS Object,

    COALESCE(p.name, s.name) AS OwnerName

    FROM sys.all_objects AS o

    INNER JOIN sys.schemas AS s ON s.schema_id = o.schema_id

    LEFT JOIN sys.database_principals AS p ON p.principal_id = o.principal_id

    WHERE COALESCE(p.name, s.name) = 'dbo'

    Once you have been able to clean up the owner/name change issues, you may want to consider adopting a change to your object creation syntax. If you use a "dbo." preface for all object creation, it won't matter who creates the object. This method may not be ideal in Development or Test environments, but would be a lot cleaner when promoting code to Production.

    Example:

    -- creates a table owned by the user I am logged in as

    CREATE TABLE MyTable (MyNumber int, MyString varchar(50))

    -- creates a table owned by "dbo"

    CREATE TABLE dbo.AnotherTable (AnotherNumber int, AnotherString varchar(50))

    Hope This Helps

    "Key"
    MCITP: DBA, MCSE, MCTS: SQL 2005, OCP