Question

With ASP.NET with C#, I am trying display numerous GridViews with different SQL commands. Because the SQL statements are long, I would like to include the variables instead of the actual statements, but I'm not sure exactly how to insert them in the SqlCommand method. Without the variable, the code appears as so

SqlCommand cmd = new SqlCommand("SELECT....; SELECT...." , myConn);

but instead of the actual statement, I'd like to replace the above sql statements with string variables like below...

string sqlVar1 = "SELECT.....";
string sqlVar2 = "SELECT....";

How do I incorporate the variables to the above code? Below does not work.

SqlCommand cmd = new SqlCommand(sqlVar1; sqlVar2, myConn);

Is there a punctuation I'm missing or perhaps additional code is required to recognize that I'm using variables instead of the actual sql statements?

Was it helpful?

Solution 2

You need to concatenate your string values together before you pass them to the constructor:

SqlCommand cmd = new SqlCommand(String.Format("{0};{1}", sqlVar1, sqlVar2), myConn);

OTHER TIPS

You simple need to concatenate the strings:

SqlCommand cmd = new SqlCommand(sqlVar1 + ';' + sqlVar2,  myConn);

If you have multipple commands - a better approach would be to use a StringBuilder to collect them and StringBuilder.ToString() as a first parameter for SqlCommand constructor:

StringBuilder sb = new StringBuilder();

sb.Append("SELECT .....;");
sb.Append("SELECT .....;");

SqlCommand cmd = new SqlCommand(sb.ToString(), myConn);

But the best approach is to set all your SELECT commands in a stored procedure and call that SP.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top