niva rojas
niva rojas

Reputation: 131

Automate Azure SQL database creation and add a database user

I'm configuring a pipeline to deploy a test environment for an app, along with app services and storage there is a SQL database. I have already automated the creation of all of them in azure and is working.

After the test is finished, the environment is destroyed to save resources until a new test is required.

Now I need to add a SQL user to the test database while deploying, it's on the same server, to simplify the login already exists, so I want to assign the same to the new database.

Something like this.

Desired:

There is a way to automate this while building the test environment?

Thanks in advance.

Upvotes: 1

Views: 312

Answers (1)

Venkataraman R
Venkataraman R

Reputation: 12959

You can go for IF NOT EXISTS and create login and user accordingly.

IF NOT EXISTS(SELECT name 
                FROM [sys].[server_principals]
                WHERE name = N'test')
 BEGIN
    CREATE LOGIN test WITH password = 'TestPassword'
 END

 IF NOT EXISTS(SELECT name 
                FROM [sys].[database_principals]
                WHERE name = N'test')
 BEGIN
    CREATE USER test for login test;
 END

Upvotes: 1

Related Questions