这是我的查询:
select EmployeeName, EmployeeSalary from Employee2
for xml path('EmployeeDetails')
返回
<EmployeeDetails>
<EmployeeName>xxxxx</EmployeeName>
<EmployeeSalary>5000.00000</EmployeeSalary>
</EmployeeDetails>
我怎样才能得到输出
<EmployeeDetails>
<EmployeeName = xxxxx />
<EmployeeSalary = 5000.00000/>
</EmployeeDetails>
答案 0 :(得分:2)
你不能,那是无效的XML
如果你想要像
这样的东西<EmployeeDetails Name="xxxxx" Salary="5000.00000" />
然后就可以做到,但这没什么区别。 XML是XML。诀窍是 AUTO 关键字
select EmployeeName, EmployeeSalary from Employee2
for xml AUTO
如果您想要精确控制XML布局,请使用这种垃圾
Select
(Select EmployeeName, EmployeeSalary From Employee2 For XML Auto, Type)
.query(
'<Slaves>{
for $employee in /Employee2
return
<Slave Name="{data($employee/@EmployeeName)}" Salary="{data($employee/@EmployeeSalary)}"/>
}</Slaves>'
)
SQL Server实际上不是XML序列化的地方。你确定你不应该在另一个组件中这样做吗?通常是您的公共接口(UI,API等)
答案 1 :(得分:1)
你应该看看For Xml Explicit。例如,使用以下模式:
Create Table #Employees
(
Id int not null identity(1,1) primary key clustered
, EmployeeName nvarchar(100) not null
, EmployeeSalary decimal(18,4) not null
)
Insert #Employees Values( 'ABC', 12345 )
Insert #Employees Values( 'DEF', 67890 )
Insert #Employees Values( 'GHI', 11223 )
以下查询:
Select 1 As Tag
, Null As Parent
, Id As [EmployeeDetails!1!Id!Hide]
, Null As [EmployeeName!2!Name]
, Null As [EmployeeSalary!3!Salary]
From #Employees
Union All
Select 2 As Tag
, 1 As Parent
, Id
, EmployeeName
, Null
From #Employees
Union All
Select 3 As Tag
, 1 As Parent
, Id
, Null
, EmployeeSalary
From #Employees As EmployeeDetails
Order By [EmployeeDetails!1!Id!Hide]
For Xml Explicit
我得到以下内容:
<EmployeeDetails>
<EmployeeName Name="ABC"/>
<EmployeeSalary Salary="12345.0000"/>
</EmployeeDetails>
<EmployeeDetails>
<EmployeeName Name="DEF"/>
<EmployeeSalary Salary="67890.0000"/>
</EmployeeDetails>
<EmployeeDetails>
<EmployeeName Name="GHI"/>
<EmployeeSalary Salary="11223.0000"/>
</EmployeeDetails>
答案 2 :(得分:0)
从Employee2中选择EmployeeName,EmployeeSalary FOR XML AUTO,ROOT('EmployeeDetails')