0

I was going over older stored procedure updating code and in one of them it was looking if a login exists. I started to change it to the way I've been using but wanted to check online to make sure. Is what is here Checking if a SQL Server login already exists better

IF NOT EXISTS
    (SELECT name
     FROM sys.database_principals
     WHERE name = 'Bob')
BEGIN
    CREATE USER [Bob] FOR LOGIN [Bob] 
END

or would this work just the same, better, worse!?

IF (ISNULL(Is_srvrolemember ('public', 'boguslogin'), 2) = 2) --any number not 1 or 0
BEGIN
    CREATE LOGIN [boguslogin] WITH PASSWORD = N'password'
END

I've been using the Is_srvrolemember one for a while now. I wanted to do this in one line without select and found this to be the easiest way. Is_srvrolemember returns a 1 if is a public login, a 0 if not and a NULL if login doesn't exist. This is also assuming a login was not explicitly removed from the public role, which isn't common and we've never done on our servers. Just curious what others think, is there any reason not to do it like this?

Now I'm wondering if I need to go back and change my code to the select statement. None of mine actually create a login but go on to do other things like send an admin email after a login fails if login does not actually exist.

DECLARE @this_login VARCHAR(200) 

IF (ISNULL(Is_srvrolemember ('public', @this_login ), 2) = 2) --any number not 1 or 0
BEGIN
                EXEC msdb.dbo.Sp_send_dbmail 
                @profile_name = @profile_name, 
                @recipients = @recipients, 
                @body = @body, 
                @subject = @subject, 
                @exclude_query_output = 0
END
Variant
  • 51
  • 6
  • 2
    Do it the "right" way. Don't check for role membership and expect a trick to work in every circumstance. – SMor Jan 24 '22 at 22:37

1 Answers1

4

I think the issue is your "I wanted to do this in one line" bit, but this is T-SQL, and that's a bad stance to take. Go with the sys.database_principals if you can. It's much cleaner.

Rob Farley
  • 15,625
  • 5
  • 44
  • 58