请参阅以下示例代码:
DECLARE @TEST TABLE (
NAME VARCHAR(100)
)
INSERT into @TEST VALUES ('NAME_1')
INSERT into @TEST VALUES ('NAME_2')
SELECT NAME AS '@NAME'
FROM @TEST
FOR XML PATH ('POSITION'), ROOT ('POSITIONS')
The result is:
<POSITIONS>
<POSITION NAME="NAME_1" />
<POSITION NAME="NAME_2" />
</POSITIONS>
I would like to condition the query to have something like this:
<POSITIONS>
<POSITION NAME_MAIN="NAME_1" />
<POSITION NAME_BACKUP="NAME_2" />
</POSITIONS>
是否可以根据查询的值调整xml属性?
when NAME IS NAME_1 THEN NAME_MAIN
when NAME IS NAME_2 THEN NAME_BACKUP?
答案 0 :(得分:2)
这可能对你有所帮助 -
DECLARE @TEST TABLE (NAME VARCHAR(100))
INSERT INTO @TEST
VALUES ('NAME_1'), ('NAME_2')
SELECT
'@NAME_MAIN' = NULLIF(NAME, 'NAME_2')
, '@NAME_BACKUP' = NULLIF(NAME, 'NAME_1')
FROM @TEST
FOR XML PATH ('POSITION'), ROOT ('POSITIONS')
输出:
<POSITIONS>
<POSITION NAME_MAIN="NAME_1" />
<POSITION NAME_BACKUP="NAME_2" />
</POSITIONS>