2012-04-20 47 views
1

我想知道如果有人可以幫助我...我有一個存儲過程,返回一個XML結果。我需要這個結果在一個文本文件保存在以下格式:在SQL Server 2008中導出xml結果txt文件

CLEAR

CHIAVE REG

VEND REP = 1,數量= 1,PRICE = 130,DES = '咖啡'

CHIU TEND = 1

數量,價格和描述來自xml結果。 這可能嗎?在此先感謝... :)

回答

0

您可以構建一個varchar字符串並將其保存到文本文件末尾。這裏的限制雖然是最大的varchar值(8000)。

我已經使用這個sproc來做到這一點;

alter PROCEDURE spWriteStringToFile 
(
@String Varchar(max), --8000 in SQL Server 2000 
@Path VARCHAR(255), 
@Filename VARCHAR(100) 

-- 
) 
AS 
DECLARE @objFileSystem int 
     ,@objTextStream int, 
     @objErrorObject int, 
     @strErrorMessage Varchar(1000), 
     @Command varchar(1000), 
     @hr int, 
     @fileAndPath varchar(80) 

set nocount on 

select @strErrorMessage='opening the File System Object' 
EXECUTE @hr = sp_OACreate 'Scripting.FileSystemObject' , @objFileSystem OUT 

Select @[email protected]+'\'[email protected] 
if @HR=0 Select @[email protected] , @strErrorMessage='Creating file "'[email protected]+'"' 
if @HR=0 execute @hr = sp_OAMethod @objFileSystem , 'CreateTextFile' 
    , @objTextStream OUT, @FileAndPath,2,True 

if @HR=0 Select @[email protected], 
    @strErrorMessage='writing to the file "'[email protected]+'"' 
if @HR=0 execute @hr = sp_OAMethod @objTextStream, 'Write', Null, @String 

if @HR=0 Select @[email protected], @strErrorMessage='closing the file "'[email protected]+'"' 
if @HR=0 execute @hr = sp_OAMethod @objTextStream, 'Close' 

if @hr<>0 
    begin 
    Declare 
     @Source varchar(255), 
     @Description Varchar(255), 
     @Helpfile Varchar(255), 
     @HelpID int 

    EXECUTE sp_OAGetErrorInfo @objErrorObject, 
     @source output,@Description output,@Helpfile output,@HelpID output 
    Select @strErrorMessage='Error whilst ' 
      +coalesce(@strErrorMessage,'doing something') 
      +', '+coalesce(@Description,'') 
    raiserror (@strErrorMessage,16,1) 
    end 
EXECUTE sp_OADestroy @objTextStream 
EXECUTE sp_OADestroy @objTextStream