Skip to content

Instantly share code, notes, and snippets.

@karkianish
Created May 8, 2019 17:31
Show Gist options
  • Save karkianish/5f5479a0f0803225c51b9b64f6a0a766 to your computer and use it in GitHub Desktop.
Save karkianish/5f5479a0f0803225c51b9b64f6a0a766 to your computer and use it in GitHub Desktop.
CREATE PROCEDURE dbo.USP_DROPANDRECREATEUSER
(@username VARCHAR(100),
@domain varchar(100))
AS
BEGIN
DECLARE @loginName VARCHAR(200) = @domain + '\' + @username;
DECLARE @script VARCHAR(MAX);
IF EXISTS (SELECT 1 FROM sys.database_principals AS s WHERE s.name = @username)
BEGIN
PRINT 'Dropping USER ' + @username + '.';
SET @script = 'DROP USER ' + @username;
EXEC (@script);
END;
PRINT 'Creating USER ' + @username + '.';
SET @script = 'CREATE USER [' + @username + '] FOR LOGIN [' + @loginName + '];';
EXEC (@script);
END;
@karkianish
Copy link
Author

karkianish commented May 8, 2019

this can be handy when using ssdt projects. if your users domain name vary across environments, you cannot create the user as a part of the ssdt project. It should be created via postdeploy script. From postdeploy script, call this stored proc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment