0

I'm trying to execute some SQL file that contain a lot of SQL files inside. Just as a main.sql that contains all the others that should be executed.

main.sql :

SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
SET ANSI_PADDING ON;

@new_instance.sql
@new_instance_tbl.sql
@new_instance_views.sql
@new_instance_tbl_configs.sql

When I open the file in my SQL Server, the red underline appears:

Incorrect syntax near '@new_instance.sql'

and then if I try to execute this, the same failure appears, so...

How can I execute different "included" .sql files from one main SQL file?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 2
    You appear to think SQL is a scripting language; it isn't and it doesn't work like one. A SQL file isn't run, the contents of the file is read, and then sent to the data engine to be run locally on the instance. Other files in the folder the SQL file was saved in are irrelevant, as it's not a "file being run". SQL isn't run like a C# application or Powershell script. – Thom A Mar 18 '22 at 13:05
  • Are you using SSMS? – Chris Schaller Mar 18 '22 at 13:11

1 Answers1

4

If you are using SSMS (SQL Server Management Studio) you can enable SQLCMD Mode

However, the syntax for referencing and executing external files is a bit different, see this answer to: TransactSQL to run another TransactSQL script

:r C:\Scripts\Script1.sql
:r C:\Scripts\Script2.sql
:r C:\Scripts\Script3.sql
Chris Schaller
  • 13,704
  • 3
  • 43
  • 81
  • You beat me to it. Adding that SQLCMD scripts can also be executed using the SQLCMD command-line utility (e.g. `SQLCMD -S YourServer -E -I -i "C:\Scripts\main.sql"`). – Dan Guzman Mar 18 '22 at 13:21