如何将 SQL Server 存储过程的输出存储在 .txt 文件中

Vik*_*s J 4 sql-server

我有这个存储过程;我正在 SSMS 中打印变量的值。相反,我想将此结果存储在一个.txt文件中。

注意:我不想使用右键单击结果然后将结果另存为的 SSMS 选项来执行此操作。我希望直接在存储过程本身中使用任何 SQL 代码/内置函数来完成它。

CREATE PROCEDURE [dbo].[usp_printresulttofile]
AS
BEGIN
    DECLARE @var NVARCHAR(MAX) = ''
    SET @var = 'print this data in txt file'

    PRINT 'Data is : ' + @var   
    /* SQL query here to store result of Print statement in text file */
END

EXEC [dbo].[usp_printresulttofile]
Run Code Online (Sandbox Code Playgroud)

在这里分享更新的工作 SP,以便它可能对有类似要求的人有用 谢谢@David Browne - Microsoft

ALTER PROCEDURE [dbo].[usp_printresulttofile]
AS
BEGIN
    DECLARE @fileTimeStamp varchar(200) =  convert(varchar,getDate(), 112 )+'_'+ Replace(convert(varchar,getDate(), 114 ),':','')  -- select convert(varchar, getdate(), 121)

    DECLARE @fileExtension varchar(5) = 'txt'
    DECLARE @var NVARCHAR(MAX) = ''
    SET @var = 'print this data in txt file'
    PRINT 'Data is : ' + @var   


  declare @fn varchar(500) = 'c:/log/SP_output_'+@fileTimeStamp+'.'+@fileExtension;
    declare @cmd varchar(8000) = concat('echo ', @var, ' > "', @fn, '"');

    print @cmd 
    exec xp_cmdshell @cmd,  no_output

    set @cmd  = concat('type "', @fn, '"');

    print @cmd 
    exec xp_cmdshell @cmd;

    END
    GO
Run Code Online (Sandbox Code Playgroud)

Dav*_*oft 5

正如评论和其他答案所表明的那样,这通常不是一个好主意。但无论如何,这里是如何做到这一点,假设您是 SQL Server 上的系统管理员。:)

-- To allow advanced options to be changed.  
EXEC sp_configure 'show advanced options', 1;  
GO  
-- To update the currently configured value for advanced options.  
RECONFIGURE;  
GO  
-- To enable the feature.  
EXEC sp_configure 'xp_cmdshell', 1;  
GO  
-- To update the currently configured value for this feature.  
RECONFIGURE;  
GO

CREATE OR ALTER PROCEDURE [dbo].[usp_printresulttofile]
AS
BEGIN
    DECLARE @var NVARCHAR(MAX) = ''
    SET @var = 'print this data in txt file'
    PRINT 'Data is : ' + @var   

    declare @fn varchar(200) = 'c:\temp\out.txt';

    declare @cmd varchar(8000) = concat('echo ', @var, ' > "', @fn, '"');

    print @cmd 
    exec xp_cmdshell @cmd,  no_output

    set @cmd  = concat('type "', @fn, '"');

    print @cmd 
    exec xp_cmdshell @cmd;


END
go
EXEC [dbo].[usp_printresulttofile]
Run Code Online (Sandbox Code Playgroud)

  • 将“>”更改为“>>”以追加而不是替换。 (2认同)