I'm trying to run this T-SQL code using SqlCommand:
USE master;
ALTER DATABASE AdventureWorks
SET SINGLE_USER;
GO
I did it like that:
public static int ObtainExclusiveAccess(Server srv, string database)
{
string cmd = @"USE master; ";
cmd += "ALTER DATABASE " + database;
cmd += @" SET SINGLE_USER ";
//cmd += "GO"; //if i add this got SqlException:
// Incorrect syntax near 'GO'
SqlConnection sqlConn =
new SqlConnection(srv.ConnectionContext.ConnectionStri ng);
sqlConn.Open(); //it's opened for sure, i've checked it
SqlCommand cmdExclusiveAccess = new SqlCommand(cmd,sqlConn);
int result = cmdExclusiveAccess.ExecuteNonQuery();
//result is -1
//string response = (string)cmdExclusiveAccess.ExecuteScalar();
//tried to get: Changed database context to 'master'. but was null
sqlConn.Close();
return result;
}
What am I doing wrong, is SqlCommand good way to run this query
ps i'am logging as user "sa" with membership db_owner, so it is not this
Thanks in advance