3

我有一个过程,需要绕过输入为空的 WHERE 子句。

请找到以下条件。

CREATE PROCEDURE [dbo].[spPERSON_SELECT]    
(
@PersonID INT = NULL,
@OrganizationID INT = NULL,
@ManagerID INT = NULL 
)
AS

BEGIN
SELECT PERSON.name, ORGANIZATION.name,PERSON.manager 
FROM PERSON 
    INNER JOIN ORGANIZATION 
        ON PERSON.person_id = ORGANIZATION.person_id    
WHERE PERSON.person_id = @PersonID  
    and ORGANIZATION.organization_id = @OrganizationID  
    and PERSON.manager_id = @ManagerID 

END
GO

当输入为空时,我面临一个问题,在这种情况下需要避免 where 条件。

例子:

如果@PersonID 为空,那么我的选择查询需要以下结构:

SELECT PERSON.name, ORGANIZATION.name,PERSON.manager 
FROM PERSON 
    INNER JOIN ORGANIZATION 
        ON PERSON.person_id = ORGANIZATION.person_id    
WHERE ORGANIZATION.organization_id = @OrganizationID
    and PERSON.manager_id = @ManagerID 

我想避免动态查询。

4

3 回答 3

5

将每个参数括起来并测试是否为空,即

(PERSON.manager_id=@ManagerID or @ManagerID is NUll)
于 2013-07-16T19:18:23.343 回答
2
SELECT PERSON.name, ORGANIZATION.name, PERSON.manager 
FROM PERSON 
INNER JOIN ORGANIZATION ON PERSON.person_id=ORGANIZATION.person_id
WHERE 
(@PersonID is null or PERSON.person_id=@PersonID) 
and (@OrganizationID is null or ORGANIZATION.organization_id=@OrganizationID)
and (@ManagerID is null or PERSON.manager_id=@ManagerID) 
于 2013-07-16T19:20:04.453 回答
2

我个人最喜欢的方法是:

WHERE PERSON.manager_id = COALESCE(@ManagerID, PERSON.manager_id)

为每个参数使用合并看起来更好。

即使@ManagerID IS NULL它总是匹配自身,它也会匹配PERSON.manager_id,但如果 停止@ManagerID IS NOT NULL

值得注意的是,您可以提供任意数量COALESCE(expression1, expression2, n)的参数。

于 2013-07-16T19:48:01.887 回答