views:

39

answers:

2

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?

+1  A: 

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()
Brad
I was trying to avoid this due to SQL injection.
madlan
@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.
Brad
Good point Brad, that's for your advice.
madlan
+1  A: 

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

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

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