我有一个存储过程,其中包含三个不同的查询,这些查询的返回值取决于接收到的变量。
它们基本上返回相同的数据,只是更改WHERE
子句:
查询:
IF @DesignType = 'BDCD'
BEGIN
SELECT
[DT].[DesignTypeGuid]
, [DT].[Name]
, [DT].[Abbreviation]
, CONVERT(BIT , IIF([DT].[DesignTypeGuid] = @ContractedDocument , 1 , 0)) AS [EnforceBaseOnPrevious]
, [DT].[Order]
FROM [DesignType] AS [DT]
WHERE [DT].[IsActive] = 1
AND ([DT].[DesignTypeGuid] != IIF(@DesignTypeGuid = @ContractedDocument , @BidDocument , @ContractedDocument))
AND [DT].[DesignTypeGuid] != @ChangeOrder
AND [DT].[DesignTypeGuid] != @AddedPart
ORDER BY
[DT].[Order]
END
ELSE
BEGIN
IF @DesignType = 'CO'
BEGIN
SELECT
[DT].[DesignTypeGuid]
, [DT].[Name]
, [DT].[Abbreviation]
, 0 AS [EnforceBaseOnPrevious]
, [DT].[Order]
FROM [DesignType] AS [DT]
WHERE [DT].[IsActive] = 1
AND [DT].[DesignTypeGuid] = @ChangeOrder
ORDER BY
[DT].[Order]
END
ELSE
BEGIN
IF @DesignType = 'AP'
BEGIN
SELECT
[DT].[DesignTypeGuid]
, [DT].[Name]
, [DT].[Abbreviation]
, 0 AS [EnforceBaseOnPrevious]
, [DT].[Order]
FROM [DesignType] AS [DT]
WHERE [DT].[IsActive] = 1
AND [DT].[DesignTypeGuid] = @AddedPart
ORDER BY
[DT].[Order]
END
有什么方法可以优化它,并通过简单的SELECT来完成,而是根据DesignType
变量进行3种不同的处理?问候
答案 0 :(得分:1)
不确定性能,但查询绝对可以写为
SELECT
[DT].[DesignTypeGuid]
, [DT].[Name]
, [DT].[Abbreviation]
, CASE @DesignType WHEN 'BDCD' THEN CONVERT(BIT , IIF([DT].[DesignTypeGuid] = @ContractedDocument , 1 , 0)) ELSE 0 END AS [EnforceBaseOnPrevious]
, [DT].[Order]
FROM [DesignType] AS [DT]
WHERE [DT].[IsActive] = 1
AND (
(
@DesignType = 'BDCD' AND [DT].[DesignTypeGuid] NOT IN ( IIF(@DesignTypeGuid = @ContractedDocument , @BidDocument , @ContractedDocument),@ChangeOrder,@AddedPart)
)
OR
(
@DesignType = 'CO' AND [DT].[DesignTypeGuid] = @ChangeOrder
)
OR
(
@DesignType = 'AP' AND [DT].[DesignTypeGuid] = @AddedPart
)
)
ORDER BY
[DT].[Order]