我正在分享下面的两个表结构。
表名:ATTRB
CMPG_ID ATTR_NAME ATTR_DESC REQUIRED TYPE ATTR_SEQ
12765 Attribute1 attribute1 1 String 2
12765 OFFERTA Offer 1 Indentification 1
表名:LEAD
CMPG_ID DYNAMIC_COLUMN
12765 <OFFERTA MaskType="Indentification">20110508</OFFERTA><Attribute1
MaskType="String">7894568978</Attribute1>
我创建了一个如下过程:
ALTER PROCEDURE [dbo].[up_Attrs_Get](
@CampaignID varchar(10))
AS
BEGIN
SELECT ATTRB.CMPG_ID AS CampaignID,
ATTRB.ATTR_NAME AS AttributeName ,
ATTRB.ATTR_DESC AS AttributeDesc,
ATTRB.REQUIRED AS Required,
CASE WHEN ATTRB.REQUIRED = 0 Then 'No'
ELSE 'Yes'
END as RequiredState,
CASE
WHEN ATTRB.TYPE <> '' THEN
ATTRB.TYPE
ELSE 'String'
END
AS AttributeType,
ATTRB.ATTR_SEQ AS AttributeSeq
FROM ATTRB
WHERE ATTRB.CMPG_ID = @CampaignID ORDER BY ATTR_SEQ
END
现在我需要提取如下结果。
CMPG_ID ATTR_NAME ATTR_DESC REQUIRED TYPE ATTR_SEQ Value
12765 Attribute1 attribute12 1 String 2 20110508
12765 OFFERTA Offer 1 Indentification 1 7894568978
“值”列显示LEAD.Dynamic列中的值提取。
感谢
答案 0 :(得分:0)
如果您知道XML中可以包含的所有元素名称(即元素名称列表是有限枚举),您可以将它们用作PIVOT的源代码(请参阅SQL Pivot运算符):
select DYNAMIC_COLUMN.value('./OFFERTA[1]','varchar(max)') AS OFFERTA
, DYNAMIC_COLUMN.value('./Attribute1[1]','varchar(max)') AS Attribute1
from LEAD
WHERE CMPG_ID = 12765
否则你可以只使用UNION值来避免使用PIVOT运算符:
select 'OFFERTA' AS ATTR_NAME, DYNAMIC_COLUMN.value('./OFFERTA[1]','varchar(max)') AS VALUE
from LEAD
WHERE CMPG_ID = 12765
UNION ALL
select 'Attribute1' AS ATTR_NAME, DYNAMIC_COLUMN.value('./Attribute1[1]','varchar(max)') AS VALUE
from LEAD
WHERE CMPG_ID = 12765
另一方面,如果你不知道所有可能的元素名称(即新元素名称可以在任何时候从外部源引入),那么它会更复杂,因为你需要使用排序对XML的“反思”。请参阅以下链接: