Microsoft sql server error 15138

SQL error 15138  occurs while dropping a user. This happens mainly when this database user owns a schema at the database level.

SQL error 15138 triggers while dropping a database user that owns some schemas at the database level.

As a part of our Server Management Services, we help our Customers to fix SQL related errors regularly.

Let us today discuss the possible causes and fixes for this error.

What is SQL error 15138?

As we discussed earlier the SQL error 15138 occurs while dropping a database user. It generally happens when the user owns some schemas at the database level. A typical error message would look like:

SQL Server error 15138

Changing the owner of the identified schema prior to dropping the user can fix it. Let us now look at the steps to perform this task.

What is SQL error 15138?

The steps to resolve the SQL error 15138 includes the following processes:

  1. Identify the schemas owned by the user
  2. Transfer the ownership of the schema
  3. Drop the User

Lets us now look at each of these in detail.

Identify the schemas owned by the user

First process to resolve the 15138 error is to identify the schemas that the user to be deleted owns. With the series of steps below, we can check the schema that a user owns in the database.

1. Connect to SQL Server Instance in SQL Server Management Studio.
2. Expand the database folder followed by the actual database name in which the user exists or created.
3. Expand Security folder inside the target database followed by the Users folder and we will find a list of database users.
4. Right-click on the user and select Properties.
5. Select Owned Schemas in the left pane of the window. A list of schemas will be displayed. The user owns the ones which are ticked.

Another option is to query schema names from sys.schemas table for the user. Here is the query:

USE DBName
GO
SELECT s.name SchemaName
FROM sys.schemas
WHERE s.principal_id = USER_ID('xyz')

Change DBName with the database name which is owned by the user “xyz”.

Transfer the ownership of the schema

Once we have identified the schemas that are owned by the user, the next step is to transfer its ownership to some other user.

We can change the owner of the schema using the ALTER AUTHORIZATION command. This command can be used to change the ownership of any securable that has an owner. We transfer the ownership to dbo, which is a type of user account in SQL Server that has permissions to perform all activities in the database. We can drop the user after changing the ownership.

To change the owner of the schema, execute the query given below:

USE [DBName]
G0
Alter Authorization ON Schema::[SCHEMA_NAME] TO [dbo]
Go

Change DBName with the database name and Schema_Name with the schema name that the user owns. This can also be done using SQL Server Management Studio. The steps to be followed for it include:

1. Connect to SQL Server Instance in SQL Server Management Studio.
2. Expand the database folder followed by the actual database name in which the user exists or created.
3. Expand Security folder inside the target database followed by the Schemas folder.
4. Right-click on the schema that has to be modified. We can see the user “xyz” as the owner. Change it to “dbo” or some other user to resolve the error. We can just enter the user and click OK to save the change or use Search to find a user.

Drop the user

As we have removed the user from the ownership of the schema, we can finally proceed to drop the user. Run below command to drop the user.

USE [DBName]
Go
DROP USER USERNAME
Go

Change DBName with the database name where the user exists and USERNAME with the user name which you want to drop.

We can perform this from SQL Server Management Studio as well by right-clicking on the user and choose the delete option.

1. Connect to target SQL Server Instance.
2. Expand the Database folder in which the user exists.
3. Expand the Security folder and then Users folder to get the target user name.
4. Right-click and choose delete on the identified user which needs to be deleted.
5. Click on the Ok button of the user deletion window.

[Need any further assistance in fixing SQL errors? – We’re available 24*7]

Conclusion

In short, SQL error 15138  occurs while dropping a user. This happens mainly when the user owns a schema at the database level. Today, we saw how our Support Engineers fix this error.

  • Remove From My Forums
  • Question

  • The title makes it sound as if question has been answered, but in fact it has not.  Because of differences.

    A db_owner created a user in the database.  This person erroneously left the default schema as dbo.  When the attempt was made to delete the user the error message cited above was received.  So created a schema in the database with the
    same name as the user.  Gave the user ownership.  Then set the default schema to be the new schema.  Tried to delete.  The schema deleted just fine.  The user refused to delete again with the error message above.  Ran below query
    to see what schemas were  owned by this user.

    SELECT name FROM sys.schemas WHERE principal_id = USER_ID(‘myuser’)

    But the query returned a result set with zero rows.  So how can this user be owning a schema when it doesn’t own any?  Why can’t we drop this user for the reason of schema ownership when it owns no schemas?


    Edward R. Joell MCSD MCDBA

    • Edited by

      Wednesday, June 20, 2012 3:52 PM
      Query hidden by formating

Answers

  • Unfortunately, I have little idea of what is going on. I see that message 15138 has a parameter where the word «schema» appears in the actual message. Maybe there is a bug so that it says «schema» when it should say something else?

    I don’t have much hope, but try this:

    SELECT ‘ IF EXISTS (SELECT * FROM sys.’ + quotename(o.name) +
           ‘ WHERE principal_id = user_id(»youruser»)) PRINT »sys.’ + o.name + »»
    FROM   sys.all_objects o
    JOIN   sys.all_columns c ON o.object_id = c.object_id
    WHERE  c.name = ‘principal_id’
      AND  o.schema_id = 4
      AND  o.type = ‘V’
      AND  o.name NOT LIKE ‘pdw%’

    Run the result set from the above, and if prints something that catalog view may be worth looking into a little more. Change «youruser» to the correct username — and of course run in the right database.


    Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se

    • Marked as answer by
      amber zhang
      Tuesday, June 26, 2012 1:27 AM
    • Unmarked as answer by
      joeller
      Monday, July 2, 2012 4:36 PM
    • Marked as answer by
      joeller
      Monday, July 2, 2012 7:01 PM

  • Erland ran your script and and ran the result set. The user showed up in two sys views, sys.database_principals and sys.schemas. (as expected)

    Then did select top 1000 from sys.shemas and altered the query to join to sys.database_principals and included name column from that view in the select.

    SELECT s.*, p.[name] 
    
    FROM sys.schemas s
    JOIN sys.database_principals p ON s.Principal_id = p.principal_id

    And that query result showed that somehow it was now showing that user as the owner of the schemas db_datareader and db_denydatareader. (!?!) For some reason this did NOT show up when we ran the query below which returned an empty result set (see OP). (Again
    !?!)

    SELECT s.name As SchemaNameResult 
    FROM sys.schemas s
    WHERE s.principal_id = USER_ID(‘youruserid’)

    So I opened the properties gui for those schemas sure enough those schemas were showing our user as the owner. (Now bear in mind that I did look in all of those property guis when the problem first occurred. I can only figure that the government database
    manager, whom I am supporting, changed something after I viewed those results.)

    Anyway, I then reset their owners back to be the roles that are supposed to own them. Voila!!! The user was able to be deleted.

    Very bizarre all around.


    Edward R. Joell MCSD MCDBA

    • Marked as answer by
      joeller
      Monday, July 2, 2012 7:01 PM

Here we will learn how to fix Microsoft SQL Server error 15138 & error 3729 that we receive while dropping a database user and a schema in SQL Server.  Let us check the details to fix this issue one after another.

Microsoft SQL Server Error 15138

I have discussed similar type of issue in my last tip, where a server level login was owner of some databases which causes to fail the login removal and throws error 15174. We changed the ownership and then tried to drop that login and it was successful.

Microsoft SQL Server Error 15138 which i am discussing in this tip is also similar kind of error. Here, user has owned some schemas at database level. We will do the same thing, we will change the owner of identified schema and drop the user.

The details of SQL Server error 15138 is given below.

Drop failed for User ‘xyz’.
The database principal owns a schema in the database, and cannot be dropped. (Microsoft SQL Server, Error:15138)

error 15138

As error clearly says that a schema is owned by this user in the database so let us check the schema that is owned by this user. Please follow the below process to check the owned schema for an user in the database.

  • Connect to SQL Server Instance in SSMS.
  • Expand the database folder followed by the actual database name in which your user exists or created.
  • Expand Security folder inside your target database followed by the Users folder and double click on the target user which you want to drop.
  • You can see a section named “Owned Schemas. Here you can see the schemas that are owned by this user.

If you find any schema that is owned by this user in above steps, you need to change the owner from this user to some other user or you can change it to dbo as well. See the below screenshot of the owned schema for a user.

owned schema

Solution

Now we have identified the schema which is owned by this user. Our Next step is to change is owner of the identified schema and then drop the login.

 --Change DBName with your database name and Schema_Name with your schema name which is owned by this user.
USE [DBName] 
G0 
Alter Authorization ON Schema::[SCHEMA_NAME] TO [dbo] 
Go

Once above command will execute, next step is to drop the user again. Run below command to drop the user.

--Change DBName with your database name where user exists and USERNAME with user name which you want to drop.
USE [DBName] 
Go 
DROP USER USERNAME 
Go

This time it will work and user will drop from the database. You can also delete this user from SSMS by right click on the user and choose the delete option. SSMS way is given below:

  • Connect to target SQL Server Instance.
  • Expand Database folder in which user exists.
  • Expand the Security folder and then Users folder to get the target user name.
  • Right click and choose delete on the identified user which needs to be deleted.
  • Click on Ok button of the user deletion window.

There are many reasons which causes to fail the user or login deletion. You can find many errors and their solutions in given links. Learn to fix:

  • Error Code 15174: Login Owns one or more databases(s). Change the owner of database(s) before dropping the login.
  • Error Code 15173: Revoke the permission(s) before dropping the login.

Microsoft SQL Server Error 3729

We have seen how to drop an user who was owner of a schema in above section. Now we will understand how to drop a schema that is referenced by an object. If you try to run DROP Schema statement and that particular schema is referenced to some object you will get below error. The details of SQL Server error 3729 is given below.

Drop failed for Schema ‘abc’.
Cannot drop schema ‘abc’ because it is being referenced by object ‘Locations’. (Microsoft SQL Server, Error 3729)

In order to fix this issue, we will change the schema of table “Locations” to remove the reference. We will use sp_changeobjectowner system stored procedure to change schema from abc to dbo. Run below command to change the schema of the table “Locations” from abc to dbo.

--Change DBName with your database name where user/schema/table exists
--Change the abc to your schema name.
USE DBName
GO
sp_changeobjectowner 'abc.Locations','dbo'

Now go ahead and drop the schema post executing above command. This time it will drop without an error.

--Change DBName with your database name where user/schema/table exists
--Change the abc to your schema name which you want to delete.
USE [DBName]
GO
DROP SCHEMA [abc]
GO

You can also drop the same using SSMS as well. Go to schema folder inside the security folder of your database. Right click on identified schema and choose delete option.  it will delete your schema.

Learn to fix below errors as well:

  • Error Code 15174: Login Owns one or more databases(s). Change the owner of database(s) before dropping the login.
  • Error Code 15173: Revoke the permission(s) before dropping the login.

I hope you like this article. Please follow us on our facebook page and on Twitter handle to get latest updates.

  • Author
  • Recent Posts

Manvendra Deo Singh

I am working as a Technical Architect in one of the top IT consulting firm. I have expertise on all versions of SQL Server since SQL Server 2000. I have lead multiple SQL Server projects like consolidation, upgrades, migrations, HA & DR. I love to share my knowledge. You can contact me on my social accounts for any consulting work.

Manvendra Deo Singh

Проблема

При восстановлении резервной копии Vault с помощью консоли ADMS возникает следующая ошибка:

«Участнику базы данных принадлежит схема в базе данных, и его нельзя удалить.»

image.png

В файле ADMSConsolelog отображается сообщение:

Connectivity.Application.VaultManager.ServiceException: The database principal owns a schema in the database, and cannot be dropped. ---> System.Data.SqlClient.SqlException: The database principal owns a schema in the database, and cannot be dropped.
   at Connectivity.Core.Database.TransactionContext.OnSqlException(SqlException e)
   at Connectivity.Core.Database.SqlAccess.ExecuteNonQueryInternal(SqlCommand cmd)
   at Connectivity.Core.Database.SqlAccess.ExecuteNonQuery(CommandType commandType, String commandText, Int32 commandTimeout, SqlParameter[] commandParameters)
   at Connectivity.Core.DataAccess.DatabaseSecurity.DropDatabaseUser(String user)
   at Connectivity.Core.DataAccess.DatabaseSecurity.ClearDatabaseUsers(String dbName)
   at Connectivity.Core.DataAccess.KnowledgeMasters.RestoreDB(String dbName, String backuppath, String dataPath, String logPath)
   at Connectivity.Core.Operations.Restore.RestoreDatabaseBackup(String databaseName, String backupLocation)
   at Connectivity.Core.Operations.Restore.RestoreKnowledgeDatabase(KnowledgeDatabase database)
   at Connectivity.Core.Operations.Restore.RestoreKnowledgeVault(KnowledgeVault vault)
   at System.Collections.Generic.List`1.ConvertAll[TOutput](Converter`2 converter)
   at Connectivity.Core.Operations.Restore.Execute()
   at Connectivity.Core.Services.KnowledgeMasterService.Restore(String restorePath, String toFSLocation, String toDBDataLocation, String toDBLogLocation, OnProgressDelegate onProgress)
   at System.Runtime.Remoting.Messaging.Message.Dispatch(Object target)
   at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg)
   --- End of inner exception stack trace ---
   at Connectivity.Application.VaultManager.ProgressCommand.Execute()
   at Connectivity.Application.VaultManager.BURWizardDataModel.InternalRestore(TypeFullOrInc type, String restorePath, LoginInfo dbLogin, String toFSLocation, String toDBDataLocation, String toDBLogLocation)
   at Connectivity.Application.VaultManager.BURWizardDataModel.DoRestore(TypeFullOrInc type, String restorePath, LoginInfo dbLogin, String toFSLocation, String toDBDataLocation, String toDBLogLocation)

В среде SQL Server Management Studio появляется сообщение:

«Участнику базы данных принадлежит схема в базе данных, и его невозможно удалить.
 (Microsoft SQL Server, ошибка: 15138)»

image.png

Причины

Сторонний поставщик (пользователь или программное обеспечение) изменил владельца схемы на сервере, создающем резервную копию. Владелец схемы должен соответствовать имени схемы. Изменение владельца схемы не поддерживается в базе данных Vault.

Это может произойти, если для резервного копирования баз данных используется стороннее решение. Это может изменить схему таким образом, чтобы при восстановлении баз данных владелец схемы отличался от ожидаемого Vault Server.

См. раздел Редактирование базы данных, содержащейся в экземпляре AUTODESKVAULT SQL вручную.

Решение

Перед созданием резервной копии на сервере в SQL Server Management Studio выполните следующие действия.
 

  1. Разверните узел «Базы данных». 
  2. Разверните каждую базу данных.
  3. Разверните узел «Безопасность». 
  4. Разверните «Схемы». 
  5. Щелкните правой кнопкой мыши на имени схемы, «Свойства». 
  6. Убедитесь, что «Владелец схемы » = » Имя схемы» (при необходимости измените владельца схемы). Нажмите «ОК».

Изображение, добавленное пользователем

Повторите шаги 5 и 6 для каждой схемы.
Повторите эти действия для базы данных

EVERY

, подключенной к экземпляру AUTODESKVAULT SQL.

Если ошибка продолжает появляться, проблема может заключаться в принадлежности ролей базы данных:

  1. Развернуть базы данных 
  2. Развернуть каждую базу данных
  3. Развернуть параметры безопасности 
  4. Развернуть роли
  5. Развернуть роли базы данных
  6. Щелкните правой кнопкой мыши имя каждой роли, выберите «Свойства» 
  7. Убедитесь, что «Owner» = dbo

Изображение, добавленное пользователем
 

См. также:

  • Резервное копирование и восстановление Vault с помощью инструментов сторонних разработчиков | Продукты Vault | Autodesk Knowledge Network

Программы

Vault Basic; Vault Professional; Vault Workgroup; Vault Manufacturing

Problem

You are trying to drop a database user, but are getting the following error message:

The database principal owns a schema in the database, and cannot be dropped. (Microsoft SQL Server, Error: 15138)

This error is self-explanatory as it tells you that the database user you are trying to drop is the database schema owner.

Resolution

To successfully drop the database user, you must find all the schemas that are owned by the database user, and then transfer their ownership to another user.

Here is the Transact-SQL script, which I wrote a while ago, to drop the database user. This script first transfer’s ownership of all database schemas associated with particular database user to the specified database user, and then drops that database user from the database.

To use this script, change the following two local variables of this script:

  • @SQLUser – Specify the name of the database user that you want to drop
  • @NewSchemaOwner – Specify the name of the database user that will be used as new schema owner for the schemas that is owned by the database user, which you are dropping
-- Ensure a USE database_name statement has been executed first.
SET NOCOUNT ON;

DECLARE @ID [int] ,
		@CurrentCommand [nvarchar](MAX) ,
		@ErrorMessage   [nvarchar](2000) ,
		@SQLUser        [sysname] , --Specify the name of the database user that you want to drop
		@NewSchemaOwner [sysname];  --Specify the name of the database user that will be used as new schema
								    --owner for the schemas that is owned by the database user you are dropping

SET @SQLUser = N'Specify_Database_User_You_Want_To_Drop'; --Example: testuser
SET @NewSchemaOwner = N'Specify_Database_User_Who_Will_User_As_New_Schema_Owner'; --Example: liveuser

DECLARE @Work_To_Do TABLE
    (
      [ID] [int] IDENTITY(1, 1)
                 PRIMARY KEY ,
      [TSQL_Text] [varchar](1024) ,
      [Completed] [bit]
    );

INSERT  INTO @Work_To_Do
        ( [TSQL_Text] ,
          [Completed]
        )
        SELECT  N'ALTER AUTHORIZATION ON SCHEMA::' + [name] + SPACE(1) + 'TO'
                + SPACE(1) + QUOTENAME(@NewSchemaOwner) ,
                0
        FROM    [sys].[schemas]
        WHERE   [principal_id] = USER_ID(@SQLUser);

INSERT  INTO @Work_To_Do
        ( [TSQL_Text] ,
          [Completed]
        )
        SELECT  N'DROP USER' + SPACE(1) + @SQLUser ,
                0

SELECT  @ID = MIN([ID])
FROM    @Work_To_Do
WHERE   [Completed] = 0;

WHILE @ID IS NOT NULL
    BEGIN
        SELECT  @CurrentCommand = [TSQL_Text]
        FROM    @Work_To_Do
        WHERE   [ID] = @ID;

        BEGIN TRY
            EXEC [sys].[sp_executesql] @CurrentCommand
            PRINT @CurrentCommand
        END TRY
        BEGIN CATCH

            SET @ErrorMessage = N'"Oops, an error occurred that could not be resolved. For more information, see below:'
                + CHAR(13) + ERROR_MESSAGE() 

            RAISERROR(@ErrorMessage,16,1) WITH NOWAIT

            GOTO ChooseNextCommand
        END CATCH

        ChooseNextCommand:

        UPDATE  @Work_To_Do
        SET     [Completed] = 1
        WHERE   [ID] = @ID

        SELECT  @ID = MIN([ID])
        FROM    @Work_To_Do
        WHERE   [Completed] = 0
    END;

SET NOCOUNT OFF;

Понравилась статья? Поделить с друзьями:
  • Microsoft sql server error 1326
  • Microsoft sql server error 10054
  • Microsoft sql native client sql server divide by zero error encountered
  • Microsoft sharepoint ошибка
  • Microsoft setup bootstrapper office 2016 ошибка