where 条件与主键上的 OR 子句

where condition with OR clause on primary keys

我正在尝试使用单个查询来获取基于 empiddeptid 的记录。 我的存储过程的输入可以是 empiddeptidempidemployees table 中的主键聚簇索引列。

查询很花时间,我停止执行它,只是想知道这个有效的场景是否考虑了主键上的 or 子句?

我正在使用 sybase

declare @emp_id int null,
@dept_id int null

select emp.* from employees emp
where
(@emp_id is null or emp.emp_id = @emp_id)
and (@dept_id is null or emp.dept_id = @dept_id)

您的 where 子句不会产生您认为应该产生的结果。照原样,它会尝试将您的 输入的 值都包含为 null 的所有记录,这可能不是您想要的。 (无论如何,这些记录是什么?)

为了得到所有输入值的记录,你需要将is nulls 切换为is not null 并交换ands 和or s.

declare @emp_id int null,
        @dept_id int null

select emp.* from employees emp
where (@emp_id is not null and emp.emp_id = @emp_id)
   or (@dept_id is not null and emp.dept_id = @dept_id)

SQL 的三值逻辑通常是其中最令人困惑的事情之一。

您的存储过程应该类似于

create procedure usp_GetEmployeeDetails
  @SearchId INT
AS
BEGIN
    SELECT EMP.*, 'EmployeeID' AS 'MatchedColumn'
    FROM 
    EMPLOYEE
    WHERE EmployeeID = @SearchId

    UNION ALL

    SELECT EMP.*, 'DepartmentID' AS 'MatchedColumn'
    FROM 
    EMPLOYEE
    WHERE DepartmentID = @SearchId
END

这适用于您拥有相同 EmployeeID 和 DepartmentId 的情况。但是,我会为两个不同的参数建议两个不同的存储过程 - 一个通过 EmployeeId 检索员工详细信息,另一个通过 DepartmentId。