Search code examples
authenticationazure-sql-databaseazure-cli

Creating a user and login or connect new user to existing sql server login with azure cli command?


I was just wondering if there is a way to create a user and either creating or connect that user to an existing azure sql server login using azure cli?

EDIT:

I would do it with something like this in sql, for example:

-- For login login_name, create a user in the database
CREATE USER <username> FOR LOGIN <login> WITH DEFAULT_SCHEMA = [dbo]
GO

-- Add user to the database owner role
EXEC sp_addrolemember N'db_owner', N'<username>'
GO

Solution

  • You can use below command to run sql query in Azure PowerShell and I followed SO-Thread:

        $servername = "sqlservername.database.windows.net"
        $databasename = "databasename"
        $username = "rithwik"
        $pass = "R!th"
        $query = "CREATE USER User2 For login xxx WITH DEFAULT_SCHEMA = [dbo]"
        $sqlCon = New-Object System.Data.SqlClient.SqlConnection
        $sqlCon.ConnectionString = "Server=$servername;Database=$databasename;User ID=$username;Password=$pass;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"
        $sqlCon.Open()
        $sqlCmd = New-Object System.Data.SqlClient.SqlCommand($query, $sqlCon)
        $sqlCmd.ExecuteNonQuery() 
        $sqlCon.Close()
    

    Here xxx is the login name.

    enter image description here

    Then the user is created:

    enter image description here

    Then you use $query = "EXEC sp_addrolemember N'db_or', N'<username>'" in place of above $query to add role.