1

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.

Gathua
  • 81
  • 1
  • 6
  • 1
    try EXEC xp_cmdshell 'sqlcmd -s "127.0.0.1" -d MyDB -i "C:\Data\ProcessedSQL\ReversalFile1.sql"' – Damith Feb 09 '15 at 09:04
  • Wouldn't you have to quote the whole command as a single string? [Here's an answer that does that](http://stackoverflow.com/a/241940/243245) but I can't believe there isn't a better way to do this, or a better option for doing this at all (e.g. put that SQL into a stored procedure?) – Rup Feb 09 '15 at 09:04
  • 1
    why to execute it when you can open it in sqlserver editor ? is there any requirement? – Ameya Deshpande Feb 09 '15 at 09:04
  • There are good reasons to run scripts from the command line - for example a script that is too big for a text editor (which SSMS is really!) – Bridge Feb 09 '15 at 09:06
  • 1
    https://msdn.microsoft.com/en-us/library/ms170572.aspx here is the link for your reference – Ameya Deshpande Feb 09 '15 at 09:08
  • 1
    I used something like this before `osql -S %ServerName% -d %DBName% -U %sql_login% -P %sql_passwd% -n -i CoreLibLUT_Insert_VoiceOverride.sql -o CoreLibLUT_Insert_VoiceOverride.out`. Generally, I use this in batch script in which I write the names of sql files in a proper sequence then give the whole package to client. they run this batch file to upgrade the DB to newest version. – Deep Feb 09 '15 at 09:08

1 Answers1

1

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

:R Pathtoyourfileinthesqlserver

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

Nick.Mc
  • 18,304
  • 6
  • 61
  • 91