Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TransactSQL to run another TransactSQL script

I have 10 transact SQL scripts that each create a table and fill it with data.

I am attempting to create 1 master sql script that will run each of the 10 other scripts.

Is there a way with TSQL / TRANSACTSQL for Microsoft SQL Server 2008 to execute another tsql script from within the current tsql script?

This is intended to be run through the SQL Server Management Studio (SSMS).

Thanks!

like image 951
Steve Stedman Avatar asked Mar 08 '11 19:03

Steve Stedman


People also ask

How do I run a SQL script from another SQL script?

If your scripts are . sql (or any kind of text) file, as @Abe Miesller says (upvoted) you can run them from within SSMS via the :r command, when SQLCMD mode is enabled. You would have to know and script the exact file path and name. This cannot be done from within a stored procedure.

Which utility can you use to execute Transact-SQL scripts from a command line?

The sqlcmd utility is a command-line utility for ad hoc, interactive execution of Transact-SQL statements and scripts and for automating Transact-SQL scripting tasks. To use sqlcmd interactively, or to build script files to be run using sqlcmd, users must understand Transact-SQL.


2 Answers

Try this if you are trying to execute a .sql file in SSMS:

:r C:\Scripts\Script1.sql :r C:\Scripts\Script2.sql :r C:\Scripts\Script3.sql ... 

note: for this to run turn on sql command mode (Query > SQLCMD Mode)

If these are scripts you run fairly often you might consider dropping them in a stored proc and running them that way...

You can also do it through sqlcmd (which I believe is more common):

sqlcmd -S serverName\instanceName -i C:\Scripts\Script1.sql 
like image 160
Abe Miessler Avatar answered Sep 19 '22 16:09

Abe Miessler


Or just use openrowset to read your script into a variable and execute it:

DECLARE @SQL varchar(MAX) SELECT @SQL = BulkColumn FROM OPENROWSET     (   BULK 'MeinPfad\MeinSkript.sql'     ,   SINGLE_BLOB ) AS MYTABLE  --PRINT @sql EXEC (@sql) 
like image 45
Pesche Helfer Avatar answered Sep 21 '22 16:09

Pesche Helfer