Click here to Skip to main content
15,565,403 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Execute query only if it is select statement. How?

i have string that contins sql selements if that statement is not update query execute the query other wise block the execution
Posted

Sounds dangerous! These restrictions should be set at database level.
Don't do it this way.
 
Share this answer
 
Comments
#realJSOP 6-Dec-11 7:58am    
This is not a permission or privilege issue. He obviously has some bizarre reason for writing this kind of code. Since he's not sharing it with us, I don't see how you can suggest this.
Michel [mjbohn] 6-Dec-11 8:38am    
Please see my comment at solution 4.
There's always a risk that the statement contains DML thus affecting the database. The proper way to ensure that no harm is done is to grant only necessary privileges to the user executing the statement. More info, see: GRANT[^].
 
Share this answer
 
C#
if (yourquery.Trim().ToUpper().StartsWith("SELECT"))
{
    // execute the query
}
 
Share this answer
 
Comments
Robert Rohde 6-Dec-11 7:34am    
Even though your solution is "a bit" better than from Uma and Derek this is still dangerous. Just because it starts with "select" it doesn't mean that it cannot modify the database.
Like mjbohn said this should be made with a specialized database user with read only access rights.
#realJSOP 6-Dec-11 7:56am    
He wanted a solution in C#. I'm assuming his query is properly formed and that he's done everything else he needs to do to make it work. I don't have the time to speculate as to whether he should do it this way or not, and I certainly wouldn't do it this way myself. That's no reason to vote my answer down.
Michel [mjbohn] 6-Dec-11 8:17am    
I agree with your perspective. And there's no reason to down vote. But isn't it important to alert OP that he's (probably) going to do dangerous things?
Robert Rohde 6-Dec-11 15:22pm    
"I'm assuming his query is properly formed and that he's done everything else he needs to do to make it work" sounds a bit naive. If he asks such a simple question do you really think he knows what he's doing...?
Heres the C# solution not sure if you wanted TSQL or C#

C#
if(yourString.ToUpper().Contains("SELECT") && !yourString.ToUpper().Contains("UPDATE"))
{
    execute the query ....
}
 
Share this answer
 
v2
Comments
Michel [mjbohn] 6-Dec-11 7:23am    
Try this string:"drop database xy; -- select"
Might be fatal
try this
C#
 string ss = "select * from tablename";
        int c = ss.IndexOf("select");
if(c>=0)
{
..executeablecode
}
else
{
return;
}
 
Share this answer
 
Comments
Michel [mjbohn] 6-Dec-11 7:23am    
Try this string:"drop database xy; -- select"
Might be fatal

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