我有一个每秒返回大量数据的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秒
有没有办法可以重写这个,以免它杀死我们?
我的王国为一个foreach !!!
答案 0 :(得分:1)
我尝试将存储过程转换为Table-Valued函数,并使网格仅从中选择所需的列。
所以你的功能仍然会选择
SELECT
[Animals].[AnimalID] AS [AnimalID],
[Animals].[name] AS [AnimalName],
[Foods].[DisplayName] AS [Food],
[Animals].[Age] AS [AnimalAge],
[Animals].[AmountOfFood] AS [AmountOfFood]
如果客户端仅选择了例如select * AnimalID, Age from myfunction(..)
,则只会将这些列传输到客户端。
答案 1 :(得分: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);