查询在sql server中使用以相同字符开头和结尾的单词来检索行

时间:2017-04-03 11:43:47

标签: sql sql-server

我需要编写一个SQL Server查询来过滤包含句子的第一个和最后一个字符的句子的行,如here

提前致谢。

3 个答案:

答案 0 :(得分:5)

我会这样做:

select t.*
from t
where left(col, 1) = right(col, 1);

默认情况下,SQL Server比较不区分大小写。如果您使用区分大小写的排序规则,则可能需要:

select t.*
from t
where lower(left(col, 1)) = lower(right(col, 1));

答案 1 :(得分:1)

像这样?

select * 
from   yourTable c
where  substring(c.yourColumn, 1, 1) = substring(c.yourColumn, len(c.yourColumn), 1)

如果您的sql server区分大小写(默认情况下不是),则需要将子字符串放在lower()函数中。

答案 2 :(得分:0)

Declare @Searchstring Varchar(2)='b'--Search charecter
;with cte1(Id, Searchstring)
As
(
SELECT 1,'EventName'                                    Union All
SELECT 2,'US colonies declare independence'             Union All
SELECT 3,'Daily Mail launched'                          Union All
SELECT 4,'India gains independence'                     Union All
SELECT 5,'DNA helix unravelled'                         Union All
SELECT 6,'Britain explodes first H bomb'                Union All
SELECT 7,'Charles de Gaulle established Fifth Republic' Union All
SELECT 8,'Harrow & WieldStone rail crash'
)
SELECT Id
    ,Searchstring
FROM cte1
WHERE CHARINDEX(@Searchstring, RIGHT(Searchstring, 1)) > 0
    AND CHARINDEX(@Searchstring, LEFT(Searchstring, 1)) > 0