Click here to Skip to main content
15,920,217 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i have three tables in all users,roles,groups


i am trying to delete userid and groupid from the roles table on selecting userid from the user table . can anyone figure out wots the problem in query.

i wrote a query but it is deleting all the records of userid and roleid in the roles table.


The query i am trying is

C#
SqlCommand cmd = new SqlCommand("Delete ROLES SELECT userid FROM users WHERE username= '" + lbldeletename.Text + "'", MAconn);



and the whole code for rowdeleting event in datagridview is

C#
protected void _rowdeleting(object sender, GridViewDeleteEventArgs e)
    {
        GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
        Label lbldeletename = (Label)row.FindControl("lblusername");
        
        MAconn.Open();
        SqlCommand cmd = new SqlCommand("Delete ROLES SELECT userid FROM users WHERE username= '" + lbldeletename.Text + "'", MAconn);
        cmd.ExecuteNonQuery();
        MAconn.Close();
        bind();

    }
Posted

The query must be as follows

SQL
"Delete FROM ROLES WHERE userid = ( SELECT userid FROM users WHERE username= '" + lbldeletename.Text + "')"


i think this may help you.
 
Share this answer
 
v2
Comments
Wendelius 9-Sep-11 9:30am    
Good answer, my 5
To add to Salini's good answer:

Don't concatenate literals to an SQL statement. Instead always use SqlParameter [^]. So your code could look something like:
C#
protected void _rowdeleting(object sender, GridViewDeleteEventArgs e)
    {
        GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
        Label lbldeletename = (Label)row.FindControl("lblusername");
        
        MAconn.Open();
        SqlCommand cmd = new SqlCommand("DELETE FROM Roles WHERE UserId = (SELECT u.UserId FROM Users u WHERE u.UserName = @UserName", MAconn);
        cmd.Parameters.AddWithValue("@UserName", lbldeletename.Text);
        cmd.ExecuteNonQuery();
        MAconn.Close();
        bind();
 
    }

This would protect you better from SqlInjections and also prevent from datatype related problems.
 
Share this answer
 
your query for deltion is incorrect. See
http://www.techonthenet.com/sql/delete.php[^] or
http://msdn.microsoft.com/en-us/library/ms189835.aspx[^]
for more information
 
Share this answer
 
Wrong query gets unexpected result.
Check the syntax. http://msdn.microsoft.com/en-us/library/ms189835.aspx[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900