一些注意事项:
[1] SSMS 中支持的 SQLCMD 脚本
https://docs.microsoft.com/en-us/sql/ssms/scripting/edit-sqlcmd-scripts-with-query-editor?view=sql-server-ver15
[2] 从上面的链接,您似乎已经阅读过(很久以前),进一步了解 :!!
那就以这个为例来看看
:!!set
...和这个一样...
!!set
无论如何,输出显示它是 SystemRoot,而不是 systemroot。
[3] SSMS 默认包含完成时间
i) 工具 > 选项 > 查询执行 > SQL Server > 高级。
ii) 取消选中显示完成时间复选框。
所以,对于答案...
:out $(SystemRoot)"\the_result.txt"
select * from myTab
:out stdout
我知道了……
<p style="color: red">
Unable to redirect output to C:\WINDOWS\the_result.txt. <br>
Access to the path 'C:\WINDOWS\the_result.txt' is denied.<br>
Msg 208, Level 16, State 1, Line 31<br>
Invalid object name 'myTab'.
</p>
...再说一次,我为什么要向 C:\WINDOWS 中的文件输出一个不存在的表的查询! ;)
让我们创建一个测试表,最终的脚本是:
--[4] Turn off (x row affected)
set nocount on
GO
create table myTab(
ID int identity(1,1) not null
,colTest varchar(20) null
);
insert into myTab
select 'Hello world';
go
--change the output to be a file in the temporary directory
--This file will be overwritten each time the script is ran
:out $(TEMP)\the_result.txt
--print this to the output
print ' <- [5] There might be squiggly bits'
print '$(SystemRoot)'
select * from myTab
go
--reset the output
:out stdout
--use type to see file contents
!!type %TEMP%\the_result.txt
--let's be tidy
!!del %TEMP%\the_result.txt
drop table myTab
go
消息输出
 <- [5] There might be squiggly bits
C:\WINDOWS
ID colTest
----------- --------------------
1 Hello world
总结
什么都不做,您可以在 SSMS 中的 SQLCMD 模式下访问环境变量一次
print '$(SystemRoot)'