调整存储过程
tweaking stored proc
我有一个使用参数调用的存储过程。我想检查 PARAM @Value 是什么,并且根据值,如果它等于某个值,我想添加 WHERE 子句的一部分。
假设过程如下所示:
Select Sum(Cost) as Cost, Car, Make
INTO #TempTable1
WHERE
1=1 and Date > '04/21/2020'
IF @Value in (1,2,3)
AND Color= 'Black'
GROUP BY
Car, Make
这是一个非常简单的代码,我的 @Value=1,2,3 的 WHERE 子句会大得多。
基本上,我的目标是在@Value = 1、2、3 的情况下添加 WHERE 子句的一部分。是否可行?
编辑:
如果在我的 select 语句上方添加类似
的内容怎么办
DECLARE @WHERE AS VARCHAR(MAX)
IF @VALUE IN (1,2,3)
SET @WHERE = 'color = ''black'''
您可以添加条件:
AND ((@VALUE IN (1,2,3) AND Color='Black') OR VALUE NOT IN (1,2,3))
或者您可以编写动态 SQL。
DECLARE @Statement NVARCHAR(1000);
SET @Statement = 'Select Sum(Cost) as Cost, Car, Make INTO #TempTable1 WHERE Date > ''04/21/2020'''
IF(@value in (1,2,3))
BEGIN
SET @Statement=@Statement+' and Color=''Black'''
END
SET @Statement=@Statement+ ' GROUP BY Car,Make '
EXEC sp_executesql @Statement
选择:
Select Sum(Cost) as Cost, Car, Make
INTO #TempTable1
WHERE
1=1 and Date > '04/21/2020'
AND
CASE WHEN @flag N (1,2,3)
THEN color
ELSE 'Black'
END = 'Black'
GROUP BY
Car, Make
最后一个选择:
IF @value in (1,2,3)
BEGIN
Select Sum(Cost) as Cost, Car, Make
INTO #TempTable1
WHERE 1=1 and Date > '04/21/2020'
AND color='Black'
GROUP BY Car, Make
END
ELSE
BEGIN
Select Sum(Cost) as Cost, Car, Make
INTO #TempTable1
WHERE 1=1 and Date > '04/21/2020'
GROUP BY Car, Make
END
我有一个使用参数调用的存储过程。我想检查 PARAM @Value 是什么,并且根据值,如果它等于某个值,我想添加 WHERE 子句的一部分。
假设过程如下所示:
Select Sum(Cost) as Cost, Car, Make
INTO #TempTable1
WHERE
1=1 and Date > '04/21/2020'
IF @Value in (1,2,3)
AND Color= 'Black'
GROUP BY
Car, Make
这是一个非常简单的代码,我的 @Value=1,2,3 的 WHERE 子句会大得多。
基本上,我的目标是在@Value = 1、2、3 的情况下添加 WHERE 子句的一部分。是否可行?
编辑: 如果在我的 select 语句上方添加类似
的内容怎么办 DECLARE @WHERE AS VARCHAR(MAX)
IF @VALUE IN (1,2,3)
SET @WHERE = 'color = ''black'''
您可以添加条件:
AND ((@VALUE IN (1,2,3) AND Color='Black') OR VALUE NOT IN (1,2,3))
或者您可以编写动态 SQL。
DECLARE @Statement NVARCHAR(1000);
SET @Statement = 'Select Sum(Cost) as Cost, Car, Make INTO #TempTable1 WHERE Date > ''04/21/2020'''
IF(@value in (1,2,3))
BEGIN
SET @Statement=@Statement+' and Color=''Black'''
END
SET @Statement=@Statement+ ' GROUP BY Car,Make '
EXEC sp_executesql @Statement
选择:
Select Sum(Cost) as Cost, Car, Make
INTO #TempTable1
WHERE
1=1 and Date > '04/21/2020'
AND
CASE WHEN @flag N (1,2,3)
THEN color
ELSE 'Black'
END = 'Black'
GROUP BY
Car, Make
最后一个选择:
IF @value in (1,2,3)
BEGIN
Select Sum(Cost) as Cost, Car, Make
INTO #TempTable1
WHERE 1=1 and Date > '04/21/2020'
AND color='Black'
GROUP BY Car, Make
END
ELSE
BEGIN
Select Sum(Cost) as Cost, Car, Make
INTO #TempTable1
WHERE 1=1 and Date > '04/21/2020'
GROUP BY Car, Make
END