I'm trying to define a database and create a table in it using a C# program. I'm using SQL server and an SQL script file that I read and execute one statement at a time, with 'GO' being the statement delimiter. The basic technique is as outlined in responses here and on MSDN - submit DDL commands via SqlCommand and ExecuteNonQuery.
Basically, I'm processing each command in the SQL script file using ExecuteNonQuery. For the USE statement, however, I'm parsing out the database name, then plugging it into a working connection string that I use in other areas of the app. I then use SqlConnection to connect to that database.
The script contains a USE [master] and then the CREATE DATABASE and a bunch of ALTERs, followed by a USE for the database just created. That's where I'm having the problem. The first USE works fine, the database is created, and each of the ALTER statements works fine too. When I hit the second USE statement, for the database that I just successfully created, I get an SqlException telling me the login failed for the user name I provided. If I leave off the user and password from the connection string, I just get the same exception telling me the login failed for user ''. BTW, before I process the second USE statement, I close the original connection (to [master]), since I'm intending to establish a new one to the new database.
The very next statement in the script is CREATE USER to define the user in the newly created database. How do I do that if I can't connect to it? Or maybe the question is how do I connect to that new database so that I can define users, and more importantly, the table(s)? I'm not sure that it's all that important for the user to be defined in the new database, but it's definitely required for the table(s) to be defined and I can't do that unless I can connect to that database.
Any thoughts? I feel like I'm missing something obvious here, but I've been beating my head against this wall for a while now.