使用SQL脚本,使用换行符创建一个文本文件

时间:2016-04-08 11:18:08

标签: sql-server tsql

我正在尝试创建包含换行符的文本文件。我有这段代码:

DECLARE @Text AS VARCHAR(100)
DECLARE @Cmd AS VARCHAR(100)

SET @Text = 'This is my text line 1 (supposed to be new line character) This is line2'
SET @Cmd ='echo ' + @Text + ' > C:\FileStore\test.txt'

EXECUTE Master.dbo.xp_CmdShell  @Cmd, NO_OUTPUT

我应该使用什么来在文本文件上添加一个新行,以便输出

This is my text line 1
This is line2

更新 我根据建议尝试了这个

SET @Text = 'This is my text line 1' + char(13) + char(10)+ 'This is line2'

但有了这个,它就不再创建txt文件了

由于

3 个答案:

答案 0 :(得分:3)

使用CHAR(13)输出回车符,或使用CHAR(13)+ CHAR(10)进行回车加换行(对于窗口)

答案 1 :(得分:2)

Windows使用回车换行符序列来表示新行,字符代码为13& 10所以:

select 'hello' + char(13) + char(10) + 'world'

(注意,在SSMS网格视图中,您只能看到一个双重空格)

  

它不再创建txt文件

啊,echo命令行不支持新行。

你可以

echo This is my text line 1 > "C:\FileStore\test.txt" & echo This is line2 >> "C:\FileStore\test.txt"

或者找到一种不涉及命令行的不同方式。

答案 2 :(得分:0)

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  


DECLARE @cmd varchar(8000), @var varchar(2000)
SET @cmd =  'echo line1 > "d:\test.txt"' 
+           '& echo line2 >> "d:\test.txt"' 
+           '& echo line3 >> "d:\test.txt"' 
+           '& echo line4 >> "d:\test.txt"' 
+           '& echo line5 >> "d:\test.txt"' 

EXEC master..xp_cmdshell @cmd; 


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', 0;  
GO  
-- To update the currently configured value for this feature.  
RECONFIGURE;  
GO