我有以下搜索sql查询:
ALTER PROCEDURE [EmployeeSearch]
@PayrollNumber varchar(50) = null,
@isInternal bit = null,
@Firstname varchar(50) = null,
@Surname varchar(50) = null
AS
SET NOCOUNT ON;
Select EmployeeSearchView.*
From EmployeeSearchView
Where
EmployeeSearchView.isInternal = @isInternal
AND
(EmployeeSearchView.PayrollNumber LIKE '%' + @PayrollNumber + '%'
OR EmployeeSearchView.Firstname LIKE '%' + @Firstname + '%'
OR EmployeeSearchView.Surname LIKE '%' + @Surname + '%'
唯一的问题是当FirstName或Surname作为空字符串发送时''它返回错误的值...如果我传递空值它可以工作..我可以修复此查询吗?
谢谢!
答案 0 :(得分:1)
你可以添加另一个和子句来检查空字符串吗?
ALTER PROCEDURE [EmployeeSearch]
@PayrollNumber varchar(50) = null,
@isInternal bit = null,
@Firstname varchar(50) = null,
@Surname varchar(50) = null
AS
SET NOCOUNT ON;
Select EmployeeSearchView.*
From EmployeeSearchView
Where
EmployeeSearchView.isInternal = @isInternal
AND
(EmployeeSearchView.PayrollNumber LIKE '%' + @PayrollNumber + ' %'
OR (@Firstname <> '' AND EmployeeSearchView.Firstname LIKE '%' + @Firstname + ' %')
OR (@Surname <> '' AND EmployeeSearchView.Surname LIKE '%' + @Surname + ' %')
答案 1 :(得分:0)
ALTER PROCEDURE [EmployeeSearch]
@PayrollNumber varchar(50) = null,
@isInternal bit = null,
@Firstname varchar(50) = null,
@Surname varchar(50) = null
AS
SET NOCOUNT ON;
IF (IsNull(@FirstName, '') = '')
SET @FirstName = '%'
ELSE
SET @FirstName = '%' + @FirstName + '%';
END
IF (IsNull(@Surname, '') = '')
SET @Surname = '%'
ELSE
SET @Surname = '%' + @Surname + '%';
END
Select EmployeeSearchView.*
From EmployeeSearchView
Where
EmployeeSearchView.isInternal = @isInternal
AND
(EmployeeSearchView.PayrollNumber LIKE '%' + @PayrollNumber + '%'
AND EmployeeSearchView.Firstname LIKE @Firstname
AND EmployeeSearchView.Surname LIKE @Surname