在SQL2000里要生成符合自己要求格式的XML可不大容易,和同事找了很多资料,终于实现了利用SQL2000存储过程生成2级菜单的XML文件。
以下是要实现的XML文件格式:
xml version ="1.0" encoding ="utf-16" ?>    
< root >
< bigsort anclassid ="62" name ="旅行与休闲" ename ="Travel & Leisure" >
< ssort id ="571" name ="箱包" ename ="Luggage & Bags" >箱包 ssort >
< ssort id ="573" name ="旅行配件" ename ="Travel Accessories" >旅行配件 ssort >
bigsort >
< bigsort anclassid ="63" name ="时尚生活" ename ="Lifestyle" >
< ssort id ="578" name ="手表" ename ="Watches" >手表 ssort >
< ssort id ="671" name ="珠宝首饰" ename ="Jewellery" >珠宝首饰 ssort >
bigsort >
root >
以下是存储过程:
CREATE PROCEDURE dbo.classes_xml
AS
DECLARE @anclassid nvarchar(50),@anclass nvarchar(50),@nclassid nvarchar(50),@nclass nvarchar(50),@xmlclass nvarchar(4000),@anclass_en nvarchar(50),@ count int,@ename nvarchar(50),@ename1 nvarchar(50),@nclass_en nvarchar(50),@count1 int
DECLARE     @ptrval binary(16)
create table ##xmltb(xmlclass ntext)
insert into ##xmltb (xmlclass) values( ' '+ char(13)+ char(10)+ ''+ char(13)+ char(10))
DECLARE @cur CURSOR
DECLARE @cur1 CURSOR
set @cur= CURSOR FOR    
select anclassid,anclass,anclass_en from bsort order by anclassidorder
open    @cur
fetch next from    @cur into @anclassid,@anclass,@anclass_en
WHILE    (@@FETCH_STATUS=0)
BEGIN
   select @ count= count(*) from products where anclassids=@anclassid and checked=1 and kucun>0
   if @ count<>0
   BEGIN
     set @ename=数据库.dbo.XML_Encode(@anclass_en)
     select @ptrval= textptr(xmlclass) from ##xmltb
     set @xmlclass= ''" name="'+@anclass+ '" ename="'+@ename+ '">'+ char(13)+ char(10)
     updatetext ##xmltb.xmlclass @ptrval NULL 0 @xmlclass
     set @cur1= CURSOR FOR    
     select nclassid,nclass,nclass_en from ssort where anclassid = @anclassid order by nclassidorder
     open    @cur1
     fetch next from    @cur1 into @nclassid,@nclass,@nclass_en
     WHILE    (@@FETCH_STATUS=0)
     BEGIN
       select @count1= count(*) from products where nclassids=@nclassid and checked=1 and kucun>0
       if @count1<>0
       BEGIN
         set @ename1=数据库.dbo.XML_Encode(@nclass_en)
         select @ptrval= textptr(xmlclass) from ##xmltb
         set @xmlclass= ''" name="'+@nclass+ '" ename="'+@ename1+ '">'+@nclass+ ' '+ char(13)+ char(10)
         updatetext ##xmltb.xmlclass @ptrval NULL 0 @xmlclass
       end
     fetch next from    @cur1 into @nclassid,@nclass,@nclass_en
     END
     close @cur1    
     deallocate @cur1
     select @ptrval= textptr(xmlclass) from ##xmltb
     set @xmlclass= ''+ char(13)+ char(10)
     updatetext ##xmltb.xmlclass @ptrval NULL 0 @xmlclass
   end
fetch next from    @cur into @anclassid,@anclass,@anclass_en
end
close @cur    
deallocate @cur
select @ptrval= textptr(xmlclass) from ##xmltb
set @xmlclass= ''+ char(13)+ char(10)
updatetext ##xmltb.xmlclass @ptrval NULL 0 @xmlclass

WHILE @@TRANCOUNT > 0
COMMIT TRAN


exec master.dbo. xp_cmdshell 'bcp "select xmlclass from 数据库.dbo.##xmltb" queryout "c:\xml\classes_cn.xml" /U"sa" /P"你的密码" /w' ,no_output    

drop table ##xmltb
GO