preety
preety

Reputation: 1066

Incorrect syntax near the keyword UNION

Can anyone tell me what wrong I have written in the following query so that this error message is being shown.

strSelectQuery = "SELECT LED_ID AS PK_ID, FIRST_NAME + ' ' + LAST_NAME AS NAME"
                        + " FROM M_LEADERLED INNER JOIN M_USER_DETAILS"
                        + " ON M_LEADERLED.LED_ID = M_USER_DETAILS.PK_ID"
                        + " WHERE (M_LEADERLED.LEADER_ID = " + Session["UserID"].ToString() + ""
                        + " AND M_USER_DETAILS.ACTIVE = 1 AND M_LEADERLED.START_DATE <= Getdate()"
                        + " AND M_LEADERLED.END_DATE > Getdate())"
                        + " UNION SELECT PK_ID, FIRST_NAME + ' ' + LAST_NAME AS NAME"
                        + " FROM M_USER_DETAILS WHERE PK_ID = " + Session["UserID"].ToString() + ";";

Upvotes: 0

Views: 3749

Answers (1)

slugster
slugster

Reputation: 49965

You need single quotes around the output of the Session["UserID"].ToString(), like this:

+ " WHERE (M_LEADERLED.LEADER_ID = '" + Session["UserID"].ToString() + "'"

Should i also mention that you should be:

  • doing a null check on Session["UserID"] before you try to ToString() it?
  • don't ever ever ever do your SQL this way if you can avoid it - it is a massive security hole (check out SQL injection)

EDIT: based on updated information supplied by the OP, because the keys are numeric you don't have to single quote them. You really do need to check the output of Session["UserID"] (because it could be garbage or null), and you need to show us the fully constructed SQL string.

Upvotes: 3

Related Questions