I am using ASP.NET (VB.NET) with SQL Server and wish to allow a user to create server logins and database users from a web form.
I have gotten this working by executing commands that create the login and user:
Dim cmd As New OleDb.OleDbCommand(
"CREATE LOGIN [" & login & "] FROM WINDOWS WITH DEFAULT_DATABASE = Db; " & _
"CREATE USER " & username & " FOR LOGIN [" & login & "]; ",
connection)
cmd.ExecuteNonQuery()
The login and username are user inputs that I am sanitizing (as best I can) and inserting directly in the CommandText. While this is working, I don't feel as if I should be doing it this way.
I'm hoping for something similar to parameterized queries, like so:
Dim cmd As New OleDb.OleDbCommand(
"CREATE LOGIN [@login] FROM WINDOWS WITH DEFAULT_DATABASE = Db; " & _
"CREATE USER @username FOR LOGIN [@login]; ",
connection)
cmd.Parameters.AddWithValue("@login", login)
cmd.Parameters.AddWithValue("@username", username)
cmd.ExecuteNonQuery()
However, this does not work because CREATE LOGIN and CREATE USER do not seem to allow parameterized values, as mentioned by podiluska:
Incorrect syntax near '@username'.
Is there a better way of creating logins and users from user input?
sp_addloginis deprecated and parameters didn't work for me. Thanks for the mentioning it though - your comment lead me to find this.