检索满足任何一个条件或两个条件的行

时间:2013-10-13 08:22:00

标签: sql-server

我的表名为 EMPLOYEE ,其中包含名字姓氏员工ID 。现在,当我单独搜索名字姓氏时,我想要获取行,或者两者都可以。怎么做?

2 个答案:

答案 0 :(得分:1)

您可以使用以下查询。我假设您有2个参数@FirstName@LastName如果您不想按它们搜索,则可以为NULL。

SELECT * FROM EMPLOYEE
WHERE ([First Name] = @FirstName OR @FirstName IS NULL)
    AND ([Last Name] = @LastName OR @LastName IS NULL)

答案 1 :(得分:0)

我会使用动态查询:

DECLARE @FirstName NVARCHAR(50), @LastName NVARCHAR(50);
SET @FirstName = 'John';
SET @LastName = 'Johnson';

DECLARE @SqlStatement NVARCHAR(MAX), @SqlParamters NVARCHAR(MAX);
SET @SqlStatement = N'SELECT e.EmployeeID, e.FirstName, e.LastName FROM dbo.Employee e
' 
+ CASE WHEN @FirstName IS NOT NULL OR @LastName IS NOT NULL THEN 'WHERE '
+ CASE WHEN @FirstName IS NOT NULL THEN 'e.FirstName = @pFirstName'
+ CASE WHEN @LastName IS NOT NULL THEN 'e.LastName = @pLastName';

-- PRINT @SqlStatement;

EXEC sp_executesql 
    @SqlStatement, 
    N'@pFirstName NVARCHAR(50), @pLastName NVARCHAR(50)',
    @pFirstName = @FirstName,
    @pLastName = @LastName;

索引:如果您有以下索引

CREATE INDEX IX_Employee_LastName_FirstName
On dbo.Employee (LastName, FirstName);

然后只有以下谓词是SARGable(Index Seek):

WHERE e.LastName = @pLastName

WHERE e.LastName = @pLastName AND e.FirstName = @pFirstName 

但以下谓词不是SARGable(索引扫描):

WHERE e.FirstName = @pFirstName