2

我有一个每秒返回大量数据并显示在网格中的 SP。我现在正在尝试减少带宽并考虑仅返回当前在我的网格中显示的列。

这当然是简化和最小化的,但基本上我所拥有的是以下 SP:

SELECT
[Animals].[AnimalID] AS [AnimalID],
[Animals].[name] AS [AnimalName],
[Foods].[DisplayName] AS [Food],
[Animals].[Age] AS [AnimalAge],
[Animals].[AmountOfFood] AS [AmountOfFood]

我目前正在尝试的是传递当前显示在网格上的字段(@fields)名称的 TVP,并仅返回必需的字段,如下所示:

SELECT
[Animals].[AnimalID] AS [AnimalID],
[Animals].[name] AS [AnimalName],
CASE 
    WHEN ('Food' in (select * from @fields)) 
    THEN [Foods].[DisplayName] 
END AS [Food],
CASE 
    WHEN ('AnimalAge' in (select * from @fields)) 
    THEN [Animals].[Age] 
END AS [AnimalAge],
CASE 
    WHEN ('AmountOfFood' in (select * from @fields)) 
    THEN [Animals].[AmountOfFood] 
END AS [AmountOfFood]

我面临的问题是(正如所料)我的 SP 从 ~200 毫秒变为 ~1 秒

有什么办法可以重写它,以免它杀死我们?

我的王国!

4

2 回答 2

1

我会尝试将存储过程转换为表值函数,并使您的网格仅从中选择所需的列。

所以你的功能仍然会选择

SELECT
[Animals].[AnimalID] AS [AnimalID],
[Animals].[name] AS [AnimalName],
[Foods].[DisplayName] AS [Food],
[Animals].[Age] AS [AnimalAge],
[Animals].[AmountOfFood] AS [AmountOfFood]

如果客户端只选择了 example select * AnimalID, Age from myfunction(..),则只有这些列会被传输到客户端。

于 2013-01-31T14:19:30.460 回答
1

在 SQL Server 中,您还可以使用动态 SQL 执行此操作。就像是:

declare @sql nvarchar(max);

select @sql = (select ', '+
                      (case when FieldName = 'Food' then 'Foods.DisplayName'
                            when FieldName = 'AnimalAge' then 'Animals.Age'
                         . . .
                       end)
               from @fields
               for xml path ('')
              );

select @sql = 'select [Animals].[AnimalID] AS [AnimalID], [Animals].[name] AS [AnimalName]'+@sql+RESTOFQUERY;

exec(@sql);
于 2013-01-31T14:28:57.390 回答