I create new logins and user in my program like this(using sql stored procedures)
//new login
SqlCommand cmd = new SqlCommand("sp_addlogin", conn);
cmd.CommandType = CommandType.StoredProcedure;
string login = radTextBox2.Text;
string password = radTextBox3.Text;
cmd.Parameters.Add(new SqlParameter("@loginame", login));
cmd.Parameters.Add(new SqlParameter("@passwd", password));
int i = cmd.ExecuteNonQuery();
....
//new user
SqlCommand cmd = new SqlCommand("sp_adduser", conn);
cmd.CommandType = CommandType.StoredProcedure;
string username = radTextBox1.Text;
string role;
try
{
switch (radDropDownList1.SelectedItem.Text)
{
case "Admin": { role = "db_owner"; break; }
case "Guest": { role = "db_datareader"; break; }
case "User": { role = "db_datawriter"; break; }
default: { this.radLabelElement1.Text = "Role was not chosen!"; return; }
}
}
catch (NullReferenceException) { this.radLabelElement1.Text = "Role was not chosen!"; return; };
string login = radTextBox2.Text;
cmd.Parameters.Add(new SqlParameter("@loginame", login));
cmd.Parameters.Add(new SqlParameter("@name_in_db", username));
cmd.Parameters.Add(new SqlParameter("@grpname", role));
int result = cmd.ExecuteNonQuery();
because I want every user of database to have either all permissions in database for admin, only read permissions for guests and read/write/update/delete permission for user for all tables in database by default.
I thought if db_owner allowed to do everything in the database, then db_datawriter allowed to read/write/update/delete data in the database and db_datareader only can read data from database. But when I use login and password for user with db_datawriter role I’ve got an exception(when I try to view datagrid) – ‘the SELECT permission was denied on the object ‘Tablename’,database ‘Databasename’,schema ‘dbo’…On the other hand user with db_datareader role can see it but cant edit(so it works correct).
What’s the problem?
If you want both read and write capabilities then they’ll need both db_datawriter and db_datareader roles. db_datawriter only grants write ability because there are use cases where you would want a user to be able to write to the database but not read from it.