Query

  • I have input parameter store procedure.  Depending on the  parameter passed in, my query have to change the field on it.  My query is:

    If @offer = 'USA'

    Begin

                   select top 5* from mytable1 where status = 'A'

    Else

                  Select top 5 * from mytable1 where status_country = 'A'

    End

     

    Can this be done in one query instead of 2 queries like above. How can I instruct my query to change the field name depending on the parametter?

    This will be a great help for me.

    Thank so much.

    Minh Vu

  • One option is using dynamic sql:

    If @offer = 'USA'

    declare @where varchar(1000)

    Begin

       set @where =    'status = ''A'''

    Else

       set @where = 'status_country = ''A'''

    End

    Exec('select top 5 * from mytable1 where '+@where)

  • Hi,

    u can do this in a single query using case statement.

     

    select top 5* from mytable1 where CASE when @offer = 'USA' THEN status

    ELSE status_country END  = 'A'

  • There's just no need for dynamic sql here ::

    The Curse and Blessings of Dynamic SQL

    Dynamic Search Conditions in T-SQL

    Arrays and Lists in SQL Server

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

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