表
| patientFirstName | patientMiddleName | patientLastName | startdate | enddate |
|------------------|-------------------|-----------------|------------|------------|
| Patient | Demo | Test | 2018-09-02 | 2018-09-08 |
| John | Doe | Demo | 2018-09-02 | 2018-09-14 |
| Demo User| | | 2018-09-18 | 2018-09-28 |
在上表中,我尝试搜索用户“ Demo User”,搜索输入为“ demouser”。我尝试修剪空白,但仍然看不到结果。
DECLARE @searchInput varchar(10)
DECLARE @startTime DATE
DECLARE @endTime DATE
SET @searchInput = 'demouser'
SET @startTime = '2018-09-18'
SET @endTime = '2018-09-28'
SELECT * FROM PatientDemoTable
WHERE (@startTime IS NULL OR startdate >= @startTime)
AND (@endTime IS NULL OR enddate <= @endTime)
AND ( LTRIM(RTRIM(@searchInput)) IS NULL OR patientFirstName like
'%'+LTRIM(RTRIM(@searchInput))+'%'
OR LTRIM(RTRIM(@searchInput)) IS NULL OR patientMiddleName like
'%'+LTRIM(RTRIM(@searchInput))+'%'
OR LTRIM(RTRIM(@searchInput)) IS NULL OR patientLastName like
'%'+LTRIM(RTRIM(@searchInput))+'%')
http://sqlfiddle.com/#!18/93ce1/33
注意:我无法像在旧版SQL Server上那样使用TRIM
答案 0 :(得分:2)
我不能像在旧版SQL Server上那样使用TRIM
好吧,您可以将 REPLACE() 函数(从SQL Server 2008开始)用作belew:
DECLARE @T TABLE
(
patientFirstName VARCHAR(50)
);
INSERT INTO @T VALUES
(' Patient '),
(' John '),
(' Demo User ');
SELECT *
FROM @T
WHERE UPPER(REPLACE(patientFirstName, ' ', '')) = UPPER('demouser');
如果您还要查找其他列,则只需添加OR
,例如:
WHERE UPPER(REPLACE(patientFirstName, ' ', '')) = UPPER('demouser')
OR UPPER(REPLACE(patientMiddleName, ' ', '')) = UPPER('demouser')
OR UPPER(REPLACE(patientLastName, ' ', '')) = UPPER('demouser');
答案 1 :(得分:0)
不可保留,但应返回所需结果
....
WHERE (@startTime IS NULL OR startdate >= @startTime)
AND (@endTime IS NULL OR enddate <= @endTime)
AND charindex(@searchInput,replace(concat(patientFirstName,'-',patientMiddleName,'-',patientLastName),' ',''))>0
注意:'-'
是可选的,它们只是防止渗色
答案 2 :(得分:0)
您可以使用以下内容:
SET @searchInput = 'demouser'
SET @searchInput = LOWER(LTRIM(RTRIM(@searchInput)))
SELECT *
FROM (
SELECT
LTRIM(RTRIM(REPLACE([patientFirstName],' ',''))) patientFirstName
, LTRIM(RTRIM(REPLACE([patientMiddleName],' ',''))) patientMiddleName
, LTRIM(RTRIM(REPLACE([patientLastName],' ',''))) patientLastName
, [startdate]
, [enddate]
FROM PatientDemoTable
) D
WHERE
(
ISNULL(@searchInput,LOWER(patientFirstName)) = LOWER(patientFirstName)
OR ISNULL(@searchInput,LOWER(patientMiddleName)) = LOWER(patientMiddleName)
OR ISNULL(@searchInput,LOWER(patientLastName)) = LOWER(patientLastName)
)
AND
(
ISNULL(@startTime, startdate) >= startdate
AND ISNULL(@endTime, enddate) <= enddate
)
LTRIM()
和RTRIM()
仅用于删除空格的保证,而REPLACE()
也将删除所有空格。 LOWER()
将所有字母都大写(如果排序规则区分大小写,则这只是数据库排序规则的一种变通方法。)
ISNULL()
将用列数据替换@searchInput
,因此如果它为NULL,它将带走所有数据(另一种解决方法将避免使用LIKE表达式。)