需要有关如何改进我的 SQL 脚本以获得更好性能的帮助。dbo.Products
表有一百万行。我很犹豫是否使用动态 SQL 重写它。谢谢!
DECLARE
@Brand varchar(MAX) = 'Brand 1, Brand 2, Brand 3',
@ItemCategory varchar(MAX) = 'IC1, IC2, IC3, IC4, IC5'
--will return all records if params where set to @Brand = NULL, @ItemCategory = NULL
SELECT
[Brand],
SUM([Amount]) AS [Amount]
FROM dbo.Products (NOLOCK)
LEFT JOIN [dbo].[Split](@Brand, ',') FilterBrand ON Brand = [FilterBrand].[Items]
LEFT JOIN [dbo].[Split](@ItemCategory, ',') FilterItemCategory ON ItemCategory = [FilterItemCategory].[Items]
WHERE
(@Brand IS NULL OR (@Brand IS NOT NULL AND [FilterBrand].[Items] IS NOT NULL)) AND
(@ItemCategory IS NULL OR (@ItemCategory IS NOT NULL AND [FilterItemCategory].[Items] IS NOT NULL))
GROUP BY
[Brand]
下面是我在网上找到的拆分表值函数:
CREATE function [dbo].[Split]
(
@String varchar(8000),
@Delimiter char(1)
)
RETURNS @Results TABLE (Items varchar(4000))
AS
BEGIN
IF (@String IS NULL OR @String = '') RETURN
DECLARE @i int, @j int
SELECT @i = 1
WHILE @i <= LEN(@String)
BEGIN
SELECT @j = CHARINDEX(@Delimiter, @String, @i)
IF @j = 0
BEGIN
SELECT @j = len(@String) + 1
END
INSERT @Results SELECT RTRIM(SUBSTRING(@String, @i, @j - @i))
SELECT @i = @j + LEN(@Delimiter)
END
RETURN
END