1

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.