I think you need to output your results to a file and bring them back in. Something like this should help get you close to what you are looking for: :setvar MyDir "C:\scripts" :OUT $(MyDir)\test.txt PRINT ':SETVAR ServerName ''' + @@SERVERNAME + '''' GO :OUT stdout :r $(MyDir)\test.txt GO SELECT $(ServerName) You can [see more examples here][1]. [1]: http://blogs.msdn.com/b/sql_server_appendix_z/archive/2013/02/23/sql-server-management-studio-sqlcmd-meets-the-richter-scale.aspx