使用组合FirstName和LastName列的搜索用户的SQL查询

时间:2018-01-11 12:46:01

标签: sql sql-server

我想在用户表中搜索应该有一个FIRSTNAME SECONDNAME选项。 例如。 “sa pe”应该找到“Sam Pethers” 另一个例子。 “Cris Jo”应该找到“Cristina Joya”。

感谢。

5 个答案:

答案 0 :(得分:1)

纯粹的猜测,但是:

CREATE TABLE #S (firstname varchar(15), secondname varchar(15));
GO
INSERT INTO #S
VALUES ('Sam','Pethers'),('Cristina','Joya');
GO

DECLARE @Search varchar(30);
SET @Search = 'sa pe';

SELECT S.*
FROM #S S
     CROSS APPLY (VALUES (CHARINDEX(' ', @Search))) CI(I)
WHERE S.firstname LIKE LEFT(@Search, CI.I - 1) + '%'
  AND S.secondname LIKE RIGHT(@Search, LEN(@Search) - CI.I) + '%';

GO

DROP TABLE #S;

答案 1 :(得分:0)

SELECT * 
FROM YourTable
WHERE FIRSTNAME LIKE '%Cris%' AND SECONDNAME LIKE '%Jo%'

答案 2 :(得分:0)

您可以在此处使用LIKE

SELECT *
FROM users
WHERE
    FIRSTNAME LIKE 'Cris%' AND LASTNAME LIKE 'Jo%';

这当然假设您的名字和姓氏存储在不同的列中。如果不是,那么你应该认真考虑将它们分开。

答案 3 :(得分:0)

如果您有两个不同的列

   SELECT * FROM 
   UserTable
   WHERE FirstName LIKE 'Sa%' AND SecondName LIKE 'Pe%'

答案 4 :(得分:0)

如果您在单列上合并名字+姓氏

,请尝试此操作
DECLARE @Srch VARCHAR(50) ='Cris Jo'
;WITH CTE
AS
(
    SELECT MyNm = 'Sam Pethers'
    UNION ALL
    SELECT MyNm = 'Cristina Joya'
)
SELECT
    *
    FROM CTE
       WHERE 
          LTRIM(RTRIM(SUBSTRING(MyNm,1,CHARINDEX(' ',MyNm)))) LIKE LTRIM(RTRIM(SUBSTRING(@Srch,1,CHARINDEX(' ',@Srch))))+'%'
          AND
          LTRIM(RTRIM(SUBSTRING(MyNm,CHARINDEX(' ',MyNm),LEN(MyNm)))) LIKE LTRIM(RTRIM(SUBSTRING(@Srch,CHARINDEX(' ',@Srch),LEN(@Srch))))+'%'

如果它们位于不同的列上

DECLARE @Srch VARCHAR(50) ='sa pe'
;WITH CTE
AS
(
    SELECT FNm = 'Sam',LNm =  'Pethers'
    UNION ALL
    SELECT FNm = 'Cristina',LNm =  'Joya'
)
SELECT
    *
    FROM CTE
       WHERE 
          FNm LIKE LTRIM(RTRIM(SUBSTRING(@Srch,1,CHARINDEX(' ',@Srch))))+'%'
          AND
          LNm LIKE LTRIM(RTRIM(SUBSTRING(@Srch,CHARINDEX(' ',@Srch),LEN(@Srch))))+'%'