0

I am on SQL Server and want to create a script that creates a database user in different databases, but I do not know which databases are available at runtime. I just want to skip user creation if a database is not available. I came up with this code:

IF EXISTS (SELECT 1 FROM sys.databases WHERE NAME = 'MyDB')
BEGIN
    IF NOT EXISTS (SELECT 1 FROM MyDB.sys.database_principals WHERE NAME = 'XUser')
    BEGIN
        /* This fails when DB MyDB is not available, despite it should not run at all */
        USE MyDB

        SELECT 'Creating User ''XUser''.'
        CREATE user XUser
        FROM LOGIN XUser
    END
    ELSE
    BEGIN
        SELECT 'User ''XUser'' in MyDB already exists, skipping creation.'
    END
    SELECT 'User ''XUser'' gets special user role in MyDB database.'
    EXEC MyDB..sp_addrolemember 'db_owner', 'SpecialUser'
END
ELSE
BEGIN
    SELECT 'Warning: DB MyDB not found. Login ''XUser'' doesn''t get additional rights on that database.'
END

But it is not working, I get

Database 'MyDB' does not exist.

the USE statement seem to be the problem, but without it the user will not be created in the right db?

How can I achive what I want?

1 Answer 1

2

You'll need to use a deferred statement here. Even though the USE statement won't be reached if the database doesn't exist, the database still needs to exist, otherwise the parser will detect the invalid database name and the statement will fail:

    PRINT N'Creating User ''XUser''.';
    EXEC sys.sp_executesql N'USE MyDB; CREATE USER XUser FROM LOGIN XUser;';

Also, don't use sp_addrolemember, it's been deprecated for at least 13 years; use ALTER ROLE.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.