[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 230
  • Last Modified:

C# String concatenation for a sql query

This is simple, but I am having trouble getting it right. I have a sql string in C# pulling data from a table. The string is:

string strData = "select * FROM vwHistory where lowTeam1 = '" + ddlTeam.SelectedValue + "' AND Year = " + ddlYear.SelectedValue + "' OR lowTeam2 = '" + ddlTeam.SelectedValue + "' AND Year = " + ddlYear.SelectedValue + " order by Date DESC, TransID DESC";

I'm getting an incorrect syntax error at the OR clause. What am I doing wrong? Thanks.
0
dodgerfan
Asked:
dodgerfan
2 Solutions
 
MajorBigDealCommented:
There is a single quote after ddlYear.SelectedValue  but none before it.
0
 
käµfm³d 👽Commented:
If you use parameterized queries, then you don't have to worry about such trivial things   ; )
0
 
Michael FowlerSolutions ConsultantCommented:
Check your quotes

"select * FROM vwHistory where lowTeam1 = '" + ddlTeam.SelectedValue + "' AND Year = " + ddlYear.SelectedValue + " OR lowTeam2 = '" + ddlTeam.SelectedValue + "' AND Year = " + ddlYear.SelectedValue + " order by Date DESC, TransID DESC";

You had an extra single quote in your string

   AND Year = " + ddlYear.SelectedValue + "'

Michael
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
dodgerfanAuthor Commented:
Thanks I knew it would be something I kept missing.
0
 
käµfm³d 👽Commented:
I certainly hope this code isn't exposed to the web...
0
 
MajorBigDealCommented:
dodgerfan, you might want to look at Linq or Entity Framework to avoid embedding raw SQL strings into your code.  It is so much easier and more flexible to debug DB-related code than the approach you are using.
0
 
niralshahCommented:
Replace your code with following code.

string strData = string.format("select * FROM vwHistory where (lowTeam1 = '{0}' AND Year={1}) OR (lowTeam2 = '{0}' AND Year = {1}) order by Date DESC, TransID DESC", ddlTeam.SelectedValue,ddlYear.SelectedValue,ddlTeam.SelectedValue);
0

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now