I have an application which can add new login to sql server and then map it to all the DB's and make it 'db_owner' (those are the requirements...). When I built the application , I used SMO and everything worked perfect. Now the requirements have changed , and I can't use SMO no longer :( So I need to run T-SQL commands from my application instead.... My problem is when I run the application nothing happens in the SQL server - the login is not added and it is not mapped to all the DB's .... but when I execute those lines in the SQL server management studio it works just fine...
those are the commands -
create login dbUser WITH PASSWORD = 'passsword';
use DB_MyLog;
create user dbUser for login dbUser;
use DB_MyLog
EXEC sp_addrolemember 'db_owner','dbUser'
In my application I run them like this -
string connString = "Data Source=" + ConfigurationManager.AppSettings.Get("localhost_SQLEXPRESS")
+ ";Initial Catalog=" + "master" + ";User ID=" + ConfigurationManager.AppSettings.Get("user")
+ ";Password=" + ConfigurationManager.AppSettings.Get("password");
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connString);
builder.AsynchronousProcessing = true;
using (SqlConnection sqlConnection1 = new SqlConnection(builder.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("CREATE LOGIN " + ConfigurationManager.AppSettings.Get("dbUser") +
" WITH PASSWORD=N'" + ConfigurationManager.AppSettings.Get("dbUserPass") + "' "
, sqlConnection1))
{
sqlConnection1.Open();
cmd.BeginExecuteNonQuery();
}
}
and in another method I run -
string connString = "Data Source=" + ConfigurationManager.AppSettings.Get("localhost_SQLEXPRESS")
+ ";Initial Catalog=" + "master" + ";User ID=" + ConfigurationManager.AppSettings.Get("user")
+ ";Password=" + ConfigurationManager.AppSettings.Get("password");
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connString);
builder.AsynchronousProcessing = true;
using (SqlConnection sqlConnection1 = new SqlConnection(builder.ConnectionString))
{
//get all databases
using (SqlCommand cmd = new SqlCommand("SELECT * FROM sys.sysdatabases", sqlConnection1))
{
sqlConnection1.Open();
SqlDataReader reader = cmd.ExecuteReader();
// Call Read before accessing data.
while (reader.Read())
{
using (SqlConnection sqlConnection2 = new SqlConnection(builder.ConnectionString))
{
sqlConnection2.Open();
using (SqlCommand cmd1 = new SqlCommand("use " + reader[0].ToString() + ";" +
"create user " + ConfigurationManager.AppSettings.Get("dbUser") + " for login " + ConfigurationManager.AppSettings.Get("dbUser") + ";" +
"use " + reader[0].ToString() +
" EXEC sp_addrolemember 'db_owner','" + ConfigurationManager.AppSettings.Get("dbUSer") + "'"
, sqlConnection2))
{
cmd1.BeginExecuteNonQuery();
}
}
}
// Call Close when done reading.
reader.Close();
}
}
BeginExecuteNonQueryand an error occurs, it only becomes visible in the callback handler. Perhaps callExecuteNonQueryinstead ofBeginExecuteNonQuery.