Newbie: Concatenating strings issue

  • Hi, I seem to have an issue with strings.  I need to create an SP that will take as parameter a column name and then run a select which will grab all row where there is an X in the specified column (char).  Here is what I need to have:

    select itemtype from import where NM = 'x'

     

    Here is my proc:

    Create procedure test (@column char(2))

    as

    exec ('select itemtype from import where' + @column + '=''x')

    go

    When I run the SP --  exec test 'NM'  I get the following message:

    Server: Msg 170, Level 15, State 1, Line 1

    Line 1: Incorrect syntax near '='.

    Server: Msg 105, Level 15, State 1, Line 1

    Unclosed quotation mark before the character string 'x'.

     

    How do I deal with this one?

    Thanks in advance..

     

  • Create procedure dbo.test (@column char(2))

    as

    exec ('select itemtype from import where ' + @column + ' = ''x''')

    go

    Make sure you read this before going down that road.

    The Curse and Blessings of Dynamic SQL

    Dynamic Search Conditions in T-SQL

  • Thanks.. it works.. I will now check your links...

Viewing 3 posts - 1 through 2 (of 2 total)

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