Will the use of CURSOR improve the performance / speed of querying using PIVOT in SQL?

不想你离开。 提交于 2020-01-06 05:53:09

问题


Newbie here on EAV (Entity-Attribute-Value) model of DB in SQL.

Just a background: I am using SQL Server 2016. The use of EAV is kind of a requirement at work so I am learning to do it one step at a time.

I recently learned how to do a dynamic PIVOT to return 800+ rows with 200+ columns in an EAV table.

See details here: Converting 200+ rows to column in SQL Server using PIVOT

As successful it was to return the data I need, the performance speed was too slow - it took about 30mins to query. By the way, I am using the code as follows:

declare @pivot_col varchar(max);
declare @sql varchar(max);

select @pivot_col = STUFF( 
                             ( SELECT ',' + CAST([Col_Name] AS VARCHAR(max) ) AS [text()]  
                             FROM ( select distinct [Col_Name] from tbl_Values ) A 
                             ORDER BY [Col_Name] FOR XML PATH('')), 1, 1, NULL
                          );

set @sql = 'SELECT * 
            FROM ( SELECT [Row_ID], [Col_Name], [Col_Value] FROM tbl_Values ) AS a 
            PIVOT (
                    MAX([Col_Value])
                    FOR [Col_Name] in (' +  @pivot_col + ' )
                  ) AS p 
            ORDER BY [Row_ID]';

exec ( @sql );

I am trying to incorporate CURSOR with this but hasn't gone much far. Before I go more distance on research, can you provide input as to if it makes any difference with regards to performance / speed?

Thanks!


回答1:


Found a solution to the poor performance of my PIVOT query: I was told to create a clustered index on the Row_ID column I have in my table. I ran the query below:

CREATE CLUSTERED INDEX IX_tbl_Values_Row_ID  
ON dbo.tbl_Values (Row_ID);   
GO  

And the query I have on my question which took 30 mins to load before had now run for just 6 seconds now! Thanks to @MohitShrivastava for the tip! Definitely worked.

I also referred to this before creating the clustered index:
https://docs.microsoft.com/en-us/sql/relational-databases/indexes/create-clustered-indexes?view=sql-server-ver15



来源:https://stackoverflow.com/questions/58949146/will-the-use-of-cursor-improve-the-performance-speed-of-querying-using-pivot-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!