1

I'm trying to execute CREATE USER with a given username (via sql parameter)

exec sp_executesql N'CREATE USER @LoginName 
                        FOR LOGIN @LoginName;',
                   N'@LoginName varchar(5)', @LoginName='myuser'

Heres the code thats generating the above:

Dim myCommand As SqlCommand = New SqlCommand("CREATE USER @LoginName 
                                                 FOR LOGIN @LoginName;", 
                                             ClassDatabaseConnection.CustomInstance)
myCommand.CommandType = CommandType.Text
myCommand.Parameters.Add("@LoginName", SqlDbType.VarChar).Value = LoginName
myCommand.ExecuteScalar()

I get and error:

Incorrect syntax near '@LoginName'.

I think this is due to the parameters being passed as VarChar causing 'MyUser' rather than MyUser

Can I not do this with sql parameters?

2 Answers 2

3

You cannot use parameters with a Create User statement. Since you're already in VB, try piecing together a statement.

Dim myCommand As SqlCommand = New SqlCommand("CREATE USER " + LoginName +
                                                " FOR LOGIN " + LoginName + ";", 
                                             ClassDatabaseConnection.CustomInstance)
myCommand.CommandType = CommandType.Text
myCommand.ExecuteScalar()
Sign up to request clarification or add additional context in comments.

2 Comments

I was trying to avoid this due to SQL injection.
@madlan, duely noted, but you can always check for mal-characters in your login name before submitting. Semi-colon, quotes, and double hyphens are a good starting point. Personally, I never allow these characters in usernames anyways.
3

As noted, you can't parameterize a CREATE LOGIN.

To avoid SQL injection (also as noted), consider using SMO Login.Create

3 Comments

I'm using .net 4 so cannot use SMO at the moment.
You'd use dmo for 2000. But CREATE LOGIN or USER is SQL Server 2005+
SMO appears to be ok with 2000 (SSMS uses it when connected to a 2000 instance).

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.