When I try and insert some results from an sp_executesql
into a variable table, I get really bad perf.
First, the query just as a simple Select.
EXEC sp_executesql N'SELECT [a].[ListingId]
FROM [dbo].[Listings] [a] LEFT OUTER JOIN
[dbo].[AgencyCompany] [b] ON [a].[AgencyCompanyId] = [b].[AgencyCompanyId]
ORDER BY UpdatedOn DESC'
This runs in a few seconds as there's a few million results to pass over the wire from a DB in the cloud to my localhost machine. So that's totally kewl.
Query plan:
Now, lets change the query to INSERT INTO
the results...
DECLARE @ListingIds TABLE (ListingId INTEGER PRIMARY KEY)
INSERT INTO @ListingIds
EXEC sp_executesql N'SELECT [a].[ListingId]
FROM [dbo].[Listings] [a] LEFT OUTER JOIN
[dbo].[AgencyCompany] [b] ON [a].[AgencyCompanyId] = [b].[AgencyCompanyId]
ORDER BY UpdatedOn DESC'
This takes about 45 seconds to return the results to my localhost machine. Same Query (well, same SELECT
query).
Lets look at the query plan...
Now lets try this with raw sql...
DECLARE @ListingIds TABLE (ListingId INTEGER PRIMARY KEY)
INSERT INTO @ListingIds
SELECT [a].[ListingId]
FROM [dbo].[Listings] [a] LEFT OUTER JOIN
[dbo].[AgencyCompany] [b] ON [a].[AgencyCompanyId] = [b].[AgencyCompanyId]
ORDER BY UpdatedOn DESC
4 seconds to run and the plan..
- So when I run the query normally, it's ok and fast.
- When I
INSERT INTO
it takes 45 odd seconds. - Same times when I have params or not.
- Same times if I use
OPTION (RECOMPILE)
or not. - Why use
sp_executesql
instead of just the raw sql statement? Because we have a heap of dynamicWHERE / AND
statements which starts to make things hard/not-that-perf-nice.
Tech..
- Sql Server 2012