Click here to Skip to main content
15,891,316 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a query to assign roles t users

C#
MAcmd.CommandText = "INSERT INTO ROLES (UserId,GroupId) SELECT UserId,GroupId FROM Users, Groups WHERE username= '" + TextBox1.Text + "' AND rolename='" + TextBox2.Text + "'";


i want to implement count sql query so that the record not repeately save in
but i don't know how to do it in C#.
e.g i found a stored procedure..

e.g
SQL
SELECT @Count = Count(UserID) FROM UserRoles WHERE
        RoleID = @RoleID AND UserID = @UserID
IF @Count = 0
		INSERT INTO UserRoles(UserID, RoleID)
		VALUES(@UserID, @RoleID)

can anyone help me to write count query ...as above store procedure for my query.
Posted

MAcmd.CommandText = SELECT Count(UserID) FROM UserRoles WHERE
RoleID = @RoleID AND UserID = @UserID"
MAcmd.ExecuteScalar()

Check the retun value of ExceuteScalar and execute the insert scripts
 
Share this answer
 
"INSERT INTO ROLES (UserId,GroupId) SELECT UserId,GroupId FROM Users, Groups WHERE username= '" + TextBox1.Text + "' AND rolename='" + TextBox2.Text + "'";

FYI, Please don't write code link this, This will create SQL Injection in your application. Use Command Parameter instead.
Just for your reference :
Introduction to SQL Injection[^]
 
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