OK, first a disclaimer. I'm using an Entity Attribute Value approach in a couple of my tables. So basically I have a List of attributes in a single column in one table that I want to then populate it in a single row in a seperate view.
I found this solution and it works great:
SQL: Dynamic view with column names based on column values in source table
However the initial load was extremely slow (it took over 27 minutes to populate 514 rows). I thought something didn't seem right at all so I messed around with selecting portions of the Client table using TOP. I got instant results. I found that I could instantly queue the entire database this way. However I found a very weird caveat. The most I could select was 5250 records.
Up to this point I was still getting instant results. If I tried to select 5251, the query hangs. I tried it on a test server and got the same limitations but with a different number (I could select a max of 5321 there). Keep in mind the table has only 514 records, so I have no idea why adding 1 number to a TOP select would cause it to hang. Does anyone have any input in this? Here's my working sql query below:
DECLARE @cols AS NVARCHAR(MAX)
DECLARE @query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(a.AttributeName)
from AttributeCodes a
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT TOP 5250 ClientID, ' + @cols + ' from
(
select c.ClientID
, c.[Value]
, a.AttributeName
from Client c
inner join AttributeCodes a
on a.AttributeCodeId = c.AttributeCodeID
)x
pivot
(
min([Value])
for AttributeName in (' + @cols + ')
)p'
execute(@query)
EDIT:
OK it seems as though the problem is that the execution plan is completely changed by adding another digit. I'll post the two results below. I still don't know why it would change, and if there is any way I can prevent it from using a Hash Match instead of an Inner Join.
Execution Plan 1 (instant):
Execution Plan 2 (30+ minutes):