I have about 500 databases that are all structured the same but the data is unique in each database. Sometimes I write dynamic SQL statements to hit all (or a subset) of those databases and will execute it with sp_ExecuteSql.
Is SQL Server able to paraellelize each batch of queries and is there a way I can tell when it will parallelize them? (I guess I could print my dynamic SQL, and copy the query batches into a new worksheet and look at the execution plan to verify if the optimizer is planning on parallelizing them.)
Typically I'm trying to aggregate the data from each database into one temp table I declare outside of the dynamic SQL. Here's an example:
DECLARE @DynamicSql AS NVARCHAR(MAX) = ''
DROP TABLE IF EXISTS #Results
SELECT TOP 0 -1 AS DatabaseId, -1 AS ResultId, -1 AS ResultValue
INTO #Results
SELECT @DynamicSql = @DynamicSql +
'
USE [' + T.DatabaseName + '];
INSERT INTO #Results
SELECT ' + CAST(T.DatabaseId AS VARCHAR(10)) + ' AS DatabaseId, T.ResultId, T.ResultValue
FROM SomeTable AS T
WHERE T.SomeCondition = ''SomeValue'';
'
FROM MyToolkit.dbo.vwDatabaseInstances
--PRINT @DynamicSql
EXEC sp_ExecuteSql @DynamicSql
SELECT *
FROM #Results
Best Answer
Looking at the execution plan, you can see that every query is done as a different query. Again, if you want to see if those query are using parallelism, you will see it in the execution plan.
If each of the query can go parallel, then they will.
Running this query agains StackOverFlow2013 DB:
you get an execution plan that does both select with parallelism.