How to run a sql file in a query in SQL Server

2019-09-06 14:00发布

问题:

I am trying to run a .sql file in SQL Server Management Studio using this command

EXEC xp_cmdshell  sqlcmd -s  '127.0.0.1' -d  MyDB -i 'C:\Data\ProcessedSQL\ReversalFile1.sql'

but I am getting an error

Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '-'

Can someone assist me please?

Update Edit: To be clear, I am only starting to use SQL Server.
I have several sql files in one folder and I was hoping to run a query window in SSMS to run several sql files one after another as follows:
Execute file1
Execute file2
Execute file3
The Files are being generated out of another system by a DBA.

回答1:

Use SSMS in SQLCMD mode to run an external SQL file:

:R Pathtoyourfileinthesqlserver

https://msdn.microsoft.com/en-us/library/ms174187.aspx