Selecting a dynamic column name

  • So here is an interesting one. We have a table that can have different columns based on the client it is running for (ex. client 1 has CRI, CCH, CWR, and client 2 has CTY, CHH, CIU). I need to select one of those columns. I have tried setting a variable to the column name and doing a SELECT @Col FROM table WHERE..., but all it returns is the value in the variable (ie. 'CRI'). How can I select a value in a dynamic column name?

    Thanks

  • Select case when @SomeVar = 'Something' THEN CRI ELSE CTY END AS Col1,... FROM dbo.YourTable.

     

    Need I point out that this is the wrong design for the system?

  • oh, the design of the system is a topic best left alone.

    unfortunately, you suggestion won't work because the column names are unknown at design time (more may be added during the year). they can't be hard coded into the SP or function.

  • In that case you should use dynamic sql... prepare the statement with and execute it using EXEC () OR SP_EXECUTESQL...

     

    MohammedU
    Microsoft SQL Server MVP

  • yeah, that's the route i'm going down now. looks like that will do the trick

  • Keep in mind the performane and security issues with dynamic sql...

    The Curse and Blessings of Dynamic SQL

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

     

    MohammedU
    Microsoft SQL Server MVP

  • Security shouldn't be an issue, as it will be within a SP or function. As for performance, well, the 'design' of our database squashes any hopes we might have...

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

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