Home Forums SQL Server 2005 T-SQL (SS2K5) Query to retrieve a column depending on variable value? RE: Query to retrieve a column depending on variable value?

  • You can do it using Dynamic sql as follows:

    --Setting up Sample Data

    Create Table Ex

    (

    ProductId Int,

    name Varchar(20),

    familyName Varchar(20),

    listPrice Int,

    price1 Int,

    price2 Int,

    price3 Int,

    price4 Int,

    price5 Int

    )

    Insert Into Ex

    Select 1,'Pepsi','Soda',10, 9, 8, 7, 6, 5

    Union ALL

    Select 2,'Coke','Soda',10, 9, 8, 7, 6, 5

    Union ALL

    Select 3,'Fanta','Soda',10, 9, 8, 7, 6, 5

    Union ALL

    Select 4,'7-Up','Soda',10, 9, 8, 7, 6, 5

    Union ALL

    Select 5,'Pepsi','Soda',10, 9, 8, 7, 6, 5

    Union ALL

    Select 6,'Marlb','Cigarrettes', 10, 9, 8, 7, 6, 5

    Union ALL

    Select 7,'Camel','Cigarrettes', 10, 9, 8, 7, 6, 5

    Union ALL

    Select 8,'7-Up','Soda',10, 9, 8, 7, 6, 5

    Union ALL

    Select 9,'Pepsi','Soda',10, 9, 8, 7, 6, 5

    Union ALL

    Select 10, 'Supe','Candies',10, 9, 8, 7, 6, 5

    Union ALL

    Select 11, 'Sugar','Candies',10, 9, 8, 7, 6, 5

    --Query for your requirement

    Declare @Soda Varchar(10), @Candies Varchar(10), @Cigarrettes Varchar(10), @sql Varchar(MAX)

    Select @Soda = 'price1', @Candies = 'price2', @Cigarrettes = 'NULL'

    Select @sql = 'Select ProductId, Name, familyName, (Case When familyName = ''Soda'' Then COALESCE(' + @Soda + ',listPrice)

    When familyName = ''Candies'' Then COALESCE(' + @Candies + ',listPrice)

    When familyName = ''Cigarrettes'' Then COALESCE(' + @Cigarrettes + ',listPrice)

    Else ''''

    END) As PriceAssigned

    From Ex'

    Execute(@sql)

    Hope this was what you were looking for.

    Vinu Vijayan

    For better and faster solutions please check..."How to post data/code on a forum to get the best help" - Jeff Moden[/url] 😉