How would I run a query inside another query in SQL Server?
NOTE: what I mean by query is the my_query_name.sql
created in SSMSSLN project solution. So I want to run my_query_name_1.sql
inside my_query_name_2.sql
.
Any idea ?
How would I run a query inside another query in SQL Server?
NOTE: what I mean by query is the my_query_name.sql
created in SSMSSLN project solution. So I want to run my_query_name_1.sql
inside my_query_name_2.sql
.
Any idea ?
Here's something to think about... It uses the BULK INSERT function to load the SQL statements into a temp table, and then uses dynamic SQL to execute them.
And yes... all the usual warning of SQL injection apply, etc, etc,
--Assume this is your main sql file.....
--Execute some SQL commands....
--Now load the second SQL file and execute it
DECLARE @SQL NVARCHAR(MAX);
CREATE TABLE #SQL (value nvarchar(max));
BULK INSERT #SQL
FROM 'C:\TEMP\select2.sql'
WITH
(
DATAFILETYPE = 'char',
FIELDTERMINATOR = '|', --<Make sure these characters
ROWTERMINATOR = '|' --<don't appear in your SQL statements
);
SELECT @SQL = Value FROM #SQL
EXEC (@SQL);
TRUNCATE TABLE #SQL;
-- Do some other sql commands in your main query
--Now load the third SQL file and execute it
BULK INSERT #SQL
FROM 'C:\TEMP\select3.sql'
WITH
(
DATAFILETYPE = 'char',
FIELDTERMINATOR = '|', --<Make sure these characters
ROWTERMINATOR = '|' --<don't appear in your SQL statements
);
SELECT @SQL = Value FROM #SQL
EXEC (@SQL);
--Do some more sql commands
--etc...
--Clean up the temp table
DROP TABLE #SQL
This approach will work without SSMS, and can be used in any environment
In SQL Server Management Studio first you will need to enable xp_cmdshell command.
-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
GO
-- To update the currently configured value for advanced options.
RECONFIGURE
GO
-- To enable the feature.
EXEC sp_configure 'xp_cmdshell', 1
GO
-- To update the currently configured value for this feature.
RECONFIGURE
GO
Then execute the command below
EXEC sys.xp_cmdshell 'sqlcmd -S (local) -d Experiments -i C:\Hello.sql'
Here, Server = (local), Database = Experiments and SQL File = C:\Hello.sql
This would successfully execute query inside a SQL file, but the output format is different than the normal.