Use SELECT result as COLUMN name in other SELECT

喜夏-厌秋 提交于 2019-12-13 12:04:27

问题


Is it possible to use the result of a select as a string to concatenate with another string in column name in other select?

Example:

SELECT brand 
FROM articles a 
WHERE a.id='12345678'

Result: BRAND_A

I now want to concatenate _PRICE to BRAND_A...

SELECT (
        SELECT brand
        FROM articles a
        WHERE a.id = '12345678'
        ) + "_PRICE"
FROM prices p
WHERE p.id = '12345678'

...to actually retrieve:

SELECT BRAND_A_PRICE
FROM prices p
WHERE p.id = '12345678'

回答1:


You don't need dynamic SQL to do this (and dynamic SQL should be avoided if at all possible). Instead you can use a CASE statement. You can do this with a single statement but I've split it out for display purposes:

DECLARE @brand VARCHAR(100) = (SELECT brand FROM articles a WHERE a.id='12345678')

SELECT CASE @brand
           WHEN 'BRAND_A' THEN BRAND_A_PRICE
           WHEN 'BRAND_B' THEN BRAND_B_PRICE
           WHEN 'BRAND_C' THEN BRAND_C_PRICE
           ELSE 0 END AS PRICE
FROM prices
WHERE id='12345678'



回答2:


I think you need a Dynamic SQL query.

First store the Brand for the particular ID in a variable then use that variable in Dynamic Query appended with the _PRICE to get the result.

DECLARE @sql   NVARCHAR(max),
        @brand VARCHAR(500)

DECLARE @sql   NVARCHAR(max),
        @brand VARCHAR(500)

SELECT @brand = brand
FROM   articles a
WHERE  a.id = '12345678'

SET @sql ='SELECT ' + @brand + '_PRICE FROM prices p WHERE p.id=''12345678'''

EXEC Sp_executesql @sql 


来源:https://stackoverflow.com/questions/27152075/use-select-result-as-column-name-in-other-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!