如何在SQL Server中删除数据库架构和用户

时间:2017-08-02 14:26:48

标签: sql-server tsql dynamic-sql

我有一个sql代码来删除架构和用户,见下文:

 USE [DB1]
GO
--SELECT * FROM sys.schemas s WHERE s.principal_id = USER_ID('ITAdmin')
WHILE EXISTS (SELECT * FROM sys.schemas s WHERE s.principal_id = USER_ID('ITAdmin'))
BEGIN
    DECLARE @tmpSchemaHolderToBeDroppedOrChanged NVARCHAR(100), @tmpAlterSchemaAuthorisationStatement NVARCHAR(200)
    SET @tmpAlterSchemaAuthorisationStatement = 'DROP SCHEMA '
    SET @tmpSchemaHolderToBeDroppedOrChanged = (SELECT TOP 1 s.name FROM sys.schemas s WHERE s.principal_id = USER_ID('ITAdmin'))
    IF @tmpSchemaHolderToBeDroppedOrChanged = 'ITAdmin'
    BEGIN
            PRINT 'Dropping ITAdmin schema.'
            IF schema_id('ITAdmin') IS NOT NULL
            BEGIN
                    DROP SCHEMA ITAdmin;
                    PRINT 'ITAdmin schema has been dropped.'
            END
    END
    ELSE
    BEGIN
            --Reassign other schemas linked to the ITAdmin user back to themselves.
            SET @tmpAlterSchemaAuthorisationStatement = 'ALTER AUTHORIZATION ON SCHEMA::'

            SET @tmpAlterSchemaAuthorisationStatement = @tmpAlterSchemaAuthorisationStatement + @tmpSchemaHolderToBeDroppedOrChanged + ' TO ' + @tmpSchemaHolderToBeDroppedOrChanged

            PRINT @tmpAlterSchemaAuthorisationStatement
            EXEC sp_executesql  @tmpAlterSchemaAuthorisationStatement
    END
END
GO
if user_id('ITAdmin') is not null
begin
    DROP USER ITAdmin;
end

它表现得已经删除了架构和用户,但它没有做应该做的事情。 我该如何修复此代码?

1 个答案:

答案 0 :(得分:2)

我使用以下脚本删除了架构和用户:

DROP SCHEMA ITAdmin
DROP USER ITAdmin

然后我执行代码,它工作了!这很奇怪,但确实有效。