sql server 删除 user,存储过程(IS2120@BG57IV3)

//z 2013-02-27 14:57:08 IS2120@BG57IV3.T1466497816.K[T218,L2950,R90,V3189]
--通过login name 删除 user 

create procedure [dbo].[sp_DropLoginFromAllDatabases](@LoginName sysname)
as
begin
  set nocount on

  declare @DBName   sysname
  declare @SQL      nvarchar(4000)
  declare @ErrorMsg nvarchar(4000)
  declare @Enter    nvarchar(2)

  set @Enter = char(13) + char(10)
 
  set @LoginName = lower(rtrim(isnull(@LoginName, '')))

  if @LoginName = ''
  begin
    set @ErrorMsg = '@LoginName cannot be null or empty'
    goto Error
  end

  if @LoginName = 'dbo'
  begin
    set @ErrorMsg = 'User [dbo] cannot be deleted'
    goto Error
  end

  if @LoginName = 'guest'
  begin
    set @ErrorMsg = 'User [guest] cannot be deleted'
    goto Error
  end

  declare DatabasesCursor cursor fast_forward
  for select name
      from master.dbo.sysdatabases
      where (status & 32) = 0 and		--Loading
            (status & 512) = 0 and		--offline
            (status & 1024) = 0 and		--read only
            (status & 32768) = 0 and		--emergency mode
            (name <> 'master')
      order by name

  open DatabasesCursor

  fetch next from DatabasesCursor
  into @DBName

  while (@@fetch_status = 0)
  begin
    set @SQL = 'if exists(select 1' + @Enter + 
               '          from ' + @DBName + '.dbo.sysusers' + @Enter + 
               '          where islogin = 1 and' + @Enter + 
               '                lower(name) = N''' + @LoginName + ''')' + @Enter + 
               'begin' + @Enter + 
               '  print(''Deleting user ['+@LoginName+'] from [' + @DBName + '] database...'')' + @Enter + 
               '  exec ' + @DBName + '.dbo.sp_dropuser N''' + @LoginName + '''' + @Enter + 
               'end'
    exec(@SQL)

 
    fetch next from DatabasesCursor
    into @DBName
  end

  close DatabasesCursor
  deallocate DatabasesCursor

  if exists(select *
            from master.dbo.syslogins
            where name = @LoginName)
  begin
    print('Deleting system login ['+@LoginName+']')
    set @SQL = 'drop login ['+@LoginName+']'
    exec(@SQL)
  end

OK:
  return 0
Error:
  set @ErrorMsg = 'Error in stored procedure sp_DropLoginFromAllDatabases:' + @Enter +
                  isnull(@ErrorMsg, '')
  raiserror(@ErrorMsg, 16, 10)
  return -1
end
posted @ 2013-02-27 14:53  BiG5  阅读(149)  评论(0编辑  收藏  举报