Tuesday, September 18, 2012

Create a database user if it doesn't already exist

Similar to OBJECT_ID function which can be used to check whether it already exists before creating/dropping, we can use SUSER_ID function check whether the database user exists before creating. This can be handy when you have a user rebuild script and it often errors out when the script tries to add a user that is already in the database
 CREATE USER [Cherry] FOR LOGIN [Cherry]
ELSE Print 'Already exists'