Ricardo Castro
Ricardo Castro

Reputation: 157

Create column name based on value without execute

I need to create a column name based on the value of other columns. I need to return a value from a column, but the specific name depends on the value insert on other table.

From intance:

Table A

Column1 | Column2
1         2

Base on that values I need to go to the table B to the column "VE12".

I need this dynamiclly, so the execute(@query) is my last option and I would like to avoid CASE WHEN statments because I have more than 50 options.

My query will be something like:

select case when fn.tab=8 and fo.pais=3 then cp.ve83 end 
FROM fn
INNER JOIN fo ON fo.stamp = fn.stamp
INNER JOIN cp

If the value in the column tab is 8 and the value in column pais is 3 I should return the value in column ve83.

Thanks for all the help!

Upvotes: 0

Views: 85

Answers (1)

Erwin Smout
Erwin Smout

Reputation: 18408

The only sensible option is to go back to the business meaning of the data and redesign the database according to that, instead of according to "technique-oriented abstractions" such as these that SQL was never intended to support.

The main reason for this is that SQL was founded on FIRST order logic, and this precludes supporting stuff like varying domains. Which you are doing (or at least seeking to do) because ve12 could be a DATETIME and ve83 could be a VARCHAR and ve56 coulb be a BLOB etc. etc. So there is just no way for you [or anyone else] to determine the data type of the results in your query, and it is even more impossible to attach meaning to what comes out of your desired query precisely because of this varying-domain and varying-source characteristic.

Upvotes: 3

Related Questions