0

I am blaming this on Monday morning, but is there some way to run a query from within a query.....

Isn't there some sort of command like

EXEC sp_ myOtherQuery.sql

I realize this lacks all sorts of error handling just wondering if there was some way to do this.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
htm11h
  • 1,739
  • 8
  • 47
  • 104
  • 1
    there's `EXEC ` -- miss off the `.sql`. – TZHX Mar 23 '15 at 16:06
  • Its not an SP though, the SP_ was a call to the default procedures that might be able to call the query to run like sp_rename when renaming tables. – htm11h Mar 23 '15 at 16:09
  • Ah, sorry. My eyes missed the space. SQL generally doesn't like working with files directly. – TZHX Mar 23 '15 at 16:11
  • SQL as a product does not really interact with .sql files. That is just how SSMS saves the files. – paparazzo Mar 23 '15 at 16:23
  • 1
    Is it possible? Yes. Is it easy to do or recommended? No. http://stackoverflow.com/questions/241925/is-it-possible-to-execute-a-text-file-from-sql-query – Stephan Mar 23 '15 at 16:41
  • Why is it not recommended? This is not a text file, it is native SQL to the same DB. No parameters will be passed. Just some processing and table copies created. – htm11h Mar 23 '15 at 17:11

2 Answers2

0

I had similar situation and used something like:

declare @cmd nvarchar(max)
declare @spname nvarchar(256)
set @spname=<your_database_name> + '.dbo.' + 'sp_executesql'
set @cmd='your query text'
execute @spname @cmd
Shkutu
  • 51
  • 4
0

If you're doing this in SQL Server Management Studio:

Turn on SQLCMD mode using the query menu. Then use the :r directive to include the other sql file into the one you're editing.

--sql statements
:r "C:\Full\Path\To\Sql\File.sql"
--More sql statements

This is effectively an include directive. The contents of the sql file will be inserted in your script at run time and the whole thing will be run as one.

This works only in SSMS. It isn't something you can do in a stored procedure.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
JC Ford
  • 6,946
  • 3
  • 25
  • 34