关于for xml子句的问题

bala7229291 2011-06-03 02:21:19

if object_id('test') is not null
drop table test
go

create table test(id int, t_name nchar(1))
go

insert into test
select 1, 'a' union all
select 2, 'b' union all
select 3, 'c' union all
select 4, 'd' union all
select 5, 'e'
go

select *
from test
for xml path('test_record'), root
go

drop table test
go


得到的结果为

<root>
<test_record>
<id>1</id>
<t_name>a</t_name>
</test_record>
<test_record>
<id>2</id>
<t_name>b</t_name>
</test_record>
<test_record>
<id>3</id>
<t_name>c</t_name>
</test_record>
<test_record>
<id>4</id>
<t_name>d</t_name>
</test_record>
<test_record>
<id>5</id>
<t_name>e</t_name>
</test_record>
</root>

但我需要在XML文本的前部加入声明


<?xml version="1.0" encoding="GBK"?>


我该如何做,是否可以加入哪个选项或者参数是的查询出来的结果中包含这个信息
...全文
102 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
bala7229291 2011-06-07
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 fallingme 的回复:]
SQL code
declare @xml xml
select @xml=(select *
from test
for xml path('test_record'), root
)
select @xml='<?xml version="1.0" encoding="GBK"?>'+cast(@xml as varchar(max))
select @xml
[/Quote]

这个语句运行是没问题,但select @xml的内容中,还是没有<?xml version="1.0" encoding="GBK"?>这个语句啊,为什么?
东那个升 2011-06-07
  • 打赏
  • 举报
回复
这貌视不是SQL能处理的
小金牛儿 2011-06-07
  • 打赏
  • 举报
回复
是不行
cosmo_sei 2011-06-04
  • 打赏
  • 举报
回复
它只生成能够放在xml的对应node,并不是整个XML文件,你得自己加上头部。
fallingme 2011-06-04
  • 打赏
  • 举报
回复
declare @xml xml
select @xml=(select *
from test
for xml path('test_record'), root
)
select @xml='<?xml version="1.0" encoding="GBK"?>'+cast(@xml as varchar(max))
select @xml
打一壶酱油 2011-06-03
  • 打赏
  • 举报
回复
不知道
bala7229291 2011-06-03
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 english_fans 的回复:]
赋值给nvarchar变量,然后加上哈,嘿嘿~
[/Quote]
有没有其他办法,声明部分应该属于XML标准的一部分,难道就没有其他自动生成的办法?
流氓兔 2011-06-03
  • 打赏
  • 举报
回复

赋值给nvarchar变量,然后加上哈,嘿嘿~

34,838

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧