我有一个过程,需要绕过输入为null的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
Iam面临一个问题,而输入为null,在这种情况下需要避免where条件。
示例:
如果@PersonID为null,那么我的select查询需要以下结构:
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
我想避免动态查询。
答案 0 :(得分:5)
括起每个参数并测试无效,即
(PERSON.manager_id=@ManagerID or @ManagerID is NUll)
答案 1 :(得分: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)
答案 2 :(得分:2)
我个人最喜欢的方法是:
WHERE PERSON.manager_id = COALESCE(@ManagerID, PERSON.manager_id)
对每个参数使用coalesce看起来更好。
即使@ManagerID IS NULL
始终匹配自己PERSON.manager_id
,也会匹配,但如果@ManagerID IS NOT NULL
则停止。
值得注意的是,您可以根据需要提供COALESCE(expression1, expression2, n)
个参数。