Search code examples
asp.net.netsql-serverauthenticationalter

SQL Server connection for ALTER LOGIN c# .net


This c# code just doesn't want to change Password on the server (UserID and PW will obviously be a strings for some purpose, but this is just to get it working):

SqlConnection conn = new SqlConnection ("Data Source=ServerIP;Persist Security Info=False;User ID=UserID;Password=UserPW");
SqlCommand cmd = new SqlCommand ("ALTER LOGIN UserID WITH PASSWORD='NewPW' OLD_PASSWORD='UserPW'", conn);
cmd.CommandType = CommandType.Text;
conn.Open();
conn.Close();

Changing Password using the same command ALTER LOGIN UserID WITH PASSWORD='NewPW' OLD_PASSWORD='UserPW' with a Server Management studio works like a charm, so there is no problem within command line or/and permissions for this particular User. I guess I miss something in Sql Connection line. Already tried combinations of:

Initial Catalog=master;
Initial Catalog=;
Integrated Security=SSPI;
Persist Security Info=True;

Changing command type, using ExecuteNonQuery();, and many other things, but nothing seems to work.

"Google" doesn't give any valuable result, hopefully I will find my answer here, thanks for taking your time in advance.


Solution

  • Try the following, works a treat for me:

    SqlConnection conn = new SqlConnection ("Data Source=ServerIP;Persist Security Info=False;User ID=UserID;Password=UserPW");
    SqlCommand cmd = new SqlCommand ("ALTER LOGIN UserID WITH PASSWORD='NewPW' OLD_PASSWORD='UserPW'", conn);
    cmd.CommandType = CommandType.Text;
    conn.Open();
    cmd.ExecuteNonQuery();
    conn.Close();
    

    You forgot to put cmd.ExecuteNonQuery() after you opened the connection. I just tested this and it successfully changed the password on my local database.