0

请看以下示例代码:

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?
4

1 回答 1

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>
于 2013-04-29T11:42:59.010 回答