如何在Sql Server中动态获取属性名称

时间:2016-06-24 10:11:21

标签: sql-server sql-server-2014-express

我有这个问题: -

select distinct pav.ProductID,pav.String_Value as Description ,pav1.String_Value as StockNumber,pav2.String_Value as ProductImage,
pav3.String_Value as SpecSheet,pav4.String_Value as Price
from core.ProductAttributesValues pav join core.Attribute a on pav.AttributeID=a.ID and a.Name='Description'
inner join core.ProductAttributesValues pav1 on pav1.ProductID=pav.ProductID
inner join core.Attribute a1 on pav1.AttributeID=a1.ID and a1.Name='StockNumber'
inner join core.ProductAttributesValues pav2 on pav2.ProductID=pav1.ProductID 
inner join core.Attribute a2 on pav2.AttributeID=a2.ID and a2.Name='ProductImage'
inner join core.ProductAttributesValues pav3 on pav3.ProductID=pav2.ProductID 
inner join core.Attribute a3 on pav3.AttributeID=a3.ID and a3.Name='SpecSheet'
inner join core.ProductAttributesValues pav4 on pav4.ProductID=pav3.ProductID 
inner join core.Attribute a4 on pav4.AttributeID=a4.ID and a4.Name='Price'

我想动态传递a1.Names(即: - Description,StockNumber,ProductImage等)。

1 个答案:

答案 0 :(得分:0)

试试这个......

SELECT 
    pav.ProductID
    ,CASE WHEN a.Name = 'Description'   THEN pav.String_Value ELSE NULL END AS Description
    ,CASE WHEN a.Name = 'StockNumber'   THEN pav.String_Value ELSE NULL END AS StockNumber
    ,CASE WHEN a.Name = 'ProductImage'  THEN pav.String_Value ELSE NULL END AS ProductImage
    ,CASE WHEN a.Name = 'SpecSheet'     THEN pav.String_Value ELSE NULL END AS SpecSheet    
    ,CASE WHEN a.Name = 'Price'         THEN pav.String_Value ELSE NULL END AS Price    
FROM core.ProductAttributesValues pav
INNER JOIN core.Attribute a ON pav.AttributeID = a.ID
    AND a.name IN ('Description', 'StockNumber', 'ProductImage', 'SpecSheet','Price')