Drop a set of users from all databases

I love my job. Really.

I received this question via email today and it was so interesting that I decided to blog it.

One of our clients used to use pdk for timesheet entry but stopped several years ago. We now have over 100 users listed in sql under multiple databases that we’d like to remove. They all end with “_pdk”. Can you come up with an efficient way (more efficient than one at a time) to delete these SQL users and any related security records in each database?

 

Does anyone have an idea? Try and answer it before you look at my answer, see if yours is better.

Please note that this will drop all users and logins that are LIKE '%PDK%'. It's unlikely that any other user will match that mask... but you should be sure.

 

DECLARE @username varchar(255)
declare @sql varchar(200)
   
DECLARE curName CURSOR LOCAL FAST_FORWARD FOR
    select rtrim(name)
        from sys.syslogins
        where name like '%pdk%'
   
OPEN curName
WHILE 1=1
BEGIN
    FETCH NEXT FROM curName INTO @username
    if @@fetch_status <> 0 begin
        break
    end
 
    set @sql = 'USE [?]; IF EXISTS(SELECT * FROM sys.database_principals WHERE name = ''' + @username + ''') DROP USER ' + @username
    print @sql
    EXEC sp_msforeachdb @sql
  
    set @sql = 'drop login ' + @username
    print @sql
    exec (@sql   )
END
CLOSE curName
DEALLOCATE curName
 
 
--select * from sys.databases

RealWorldCode gives developers practical, real‑world solutions with clean, working code — no fluff, no theory, just answers.
Links
Home
Knowledge Areas
Sitemap
Contact
Et cetera
Privacy Policy
Terms and Conditions
Cookie Preferences