Incorrect syntax near 'CHAR'

  • I am getting syntax error with the following:

    WHERE ' + @FieldName + ' = ' + CHAR(39) + @FieldValue + CHAR(39)

    what is wrong?

    Thanks.

  • I assume that the @FieldName variable contains a column name that you want use in your where clause? You need to use dynamic SQL if that is the case. Of course, you could already be using dynamic SQL; I can't tell from your post.

    It would help if you posted the whole SQL statement and not just a piece.

    John Rowan

    ======================================================
    ======================================================
    Forum Etiquette: How to post data/code on a forum to get the best help[/url] - by Jeff Moden

  • Thanks John for your prompt reply. Here is my whole query:

    EXEC ('Select *

    FROM Table1

    WHERE ' + @FieldName + ' = ' + CHAR(39) + @FieldValue + CHAR(39)

    + ' order by 1')

  • Assign your SQL code into a variable and then execute the variable. You should look into using sp_executeSQL when executing dynamic SQL.

    SET @sqlcmd ='Select * FROM Table1 WHERE ' + @FieldName + ' = ' + CHAR(39) + FieldValue + CHAR(39) + ' order by 1'

    EXEC (@sqlcmd)

    John Rowan

    ======================================================
    ======================================================
    Forum Etiquette: How to post data/code on a forum to get the best help[/url] - by Jeff Moden

  • Thank you again John, that worked. Your help is truly appreciated.

  • No problem. For what it's worth, check out this link on dynamic SQL.

    http://www.sommarskog.se/dynamic_sql.html

    John Rowan

    ======================================================
    ======================================================
    Forum Etiquette: How to post data/code on a forum to get the best help[/url] - by Jeff Moden

  • Thanks again, John. You have been very helpful. The article taught me so much.

Viewing 7 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply