我正在使用t-sql,但我想我的问题更笼统。
在我的应用中,用户尝试获取给定部分名称的匹配条目。我的查询尝试查找与名字,姓氏和电子邮件匹配的内容:
...
WHERE FirstName LIKE ('%' + @name + '%')
OR LastName LIKE ('%' + @name + '%')
OR EMail LIKE ('%' + @name + '%')
我想知道查询本身是否有一种简单的方法来确定条件的哪一部分实际成功。问候。
答案 0 :(得分:1)
SELECT 'FirstName ', ... FROM ... WHERE FirstName LIKE ('%' + @name + '%')
UNION
SELECT 'LastName ', ... FROM ... WHERE LastName LIKE ('%' + @name + '%')
UNION
SELECT 'EMail ', ... FROM ... WHERE EMail LIKE ('%' + @name + '%')
或CASE .. WHEN
SELECT
CASE
WHEN FirstName LIKE ('%' + @name + '%') THEN 'FirstName'
WHEN LastName LIKE ('%' + @name + '%') THEN 'LastName'
WHEN EMail LIKE ('%' + @name + '%') THEN 'EMail ', *
FROM ... WHERE ...
UPD删除重复项并获得所有匹配项
;WITH x AS
(
SELECT [M] = 1, ... FROM ... WHERE FirstName LIKE ('%' + @name + '%')
UNION ALL
SELECT [M] = 2, ... FROM ... WHERE LastName LIKE ('%' + @name + '%')
UNION ALL
SELECT [M] = 4, ... FROM ... WHERE EMail LIKE ('%' + @name + '%')
),
(
SELECT FirstName, LastName , EMail, [SM] = SUM(M)
FROM x
GROUP BY FirstName, LastName , EMail
)
SELECT FirstName, LastName , EMail,
IIF([SM]&1<>0, 'FirstName;','') +
IIF([SM]&2<>0, 'LastName;','') +
IIF([SM]&4<>0, 'EMail;','') as [Match]
FROM x
答案 1 :(得分:0)
我会这样做;
select t.*
from (select t.*,
( (case when FirstName LIKE ('%' + @name + '%') then 'FirstName'' else '' end) +
(case when LastName LIKE ('%' + @name + '%') then 'LastName'' else '' end) +
(case when Email LIKE ('%' + @name + '%') then 'Email'' else '' end)
) as matches
from t
) t
where matches <> '';
这考虑到可能有不止一列匹配。