0

我有一个名为EMPLOYEE的表,其中包含First NameLast NameEmployee ID。现在,当我单独搜索名字或姓氏时,我想获得行,或者可能两者兼而有之。怎么做?

4

2 回答 2

1

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

SELECT * FROM EMPLOYEE
WHERE ([First Name] = @FirstName OR @FirstName IS NULL)
    AND ([Last Name] = @LastName OR @LastName IS NULL)
于 2013-10-13T08:24:00.770 回答
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 
于 2013-10-13T08:57:49.303 回答