1

I have got this code below which should:

Select column odjezd
From table stanice 
Order by odjezd
where akce=zakce.Text

SqlCommand combobox = new SqlCommand("SELECT odjezd FROM stanice 
                                      ORDER BY odjezd ASC 
                                      WHERE akce="+zakce.Text, spojeni);

It gives me this error: Incorrect syntax near WHERE.

Would someone please improve my code? Thanks in advance

6 Answers 6

6

You're ORDER BY clause must be last and you are missing the single quotes around your string in WHERE clause.

By the way you should use a parameter instead string manipulation for your command text, to prevent from SQL injection.

var command = new SqlCommand("SELECT odjezd FROM stanice WHERE akce=@akce ORDER BY odjezd ASC", spojeni);
command.Parameters.Add(new SqlParameter("@akce", zakce.Text));
Sign up to request clarification or add additional context in comments.

Comments

3

ORDER BY has to go for last....

You

  • first query for your data
  • after order it accordingly

So it will become like:

var command new SqlCommand("SELECT odjezd FROM stanice WHERE akce="
                             + zakce.Text + " ORDER BY odjezd ASC", spojeni)

1 Comment

And you should always use parametrized queries - do not concatenate together your SQL like this - highly vulnerable to SQL injection attacks ....
2

please try this code:

SqlCommand combobox = new SqlCommand("SELECT odjezd FROM stanice WHERE akce='"+zakce.Text + "' ORDER BY odjezd ASC", spojeni);

I hope it would work for you.

ORDER BY

has to go last.

Comments

2

Where clause goes before order by

Comments

1

ORDER BY should go after WHERE, and I believe you'll need a single quote arount what you're searching for.

SqlCommand combobox = new SqlCommand("SELECT odjezd FROM stanice WHERE akce='"+zakce.Text + "' ORDER BY odjezd ASC", spojeni);

Comments

1

Your statement is not ordered correctly, a handy run down of SELECT statement ordering can be found here (amongst other places): http://msdn.microsoft.com/en-us/library/ms189499.aspx

So in your case, you would want to order your statement thusly:

SELECT odjezd 
FROM stanice 
WHERE ...
ORDER BY odjezd ASC 

As Woni has pointed out, it would also be better if you utilised SqlCommand.Parameters, to enforce correct data types, and protect you against potential exploits.

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.