如何在SQL Server中获取精确单词的char索引

时间:2015-03-12 06:05:47

标签: sql sql-server

Begin Tran

Declare @Ssql As Varchar(100)
Set @Ssql = 'India is mycountry. I love my country and I am proud of its rich and varied heritage'

Select charindex('country', lower(@Ssql))

RollBack

此查询返回12而不是31。

好的,现在我想要country [更晚]的单词的char索引,而不是country [previous]中单词mycountry的char索引。

我该怎么做?

请帮忙。

4 个答案:

答案 0 :(得分:2)

以下代码将为您提供serachchar的最后一次出现。多次使用REVERSE函数会对性能产生不利影响

DECLARE @Ssql VARCHAR(500) = 'India is my country. I love my country and I am proud of its rich and varied heritage'
DECLARE @FindChar VARCHAR(7) = 'country'

-- Shows the position of the last occurrence
SELECT LEN(@Ssql) - CHARINDEX(@FindChar,REVERSE(@Ssql)) AS LastOccuredAt

-- Shows text before last occurrence
SELECT LEFT(@Ssql , LEN(@Ssql ) - CHARINDEX(@FindChar,REVERSE(@Ssql ))) AS Before

-- Shows text after last occurrence
SELECT RIGHT(@Ssql , CHARINDEX(@FindChar,REVERSE(@Ssql))-1) AS After

如果您的searchchar将多次出现并且您想要2nd出现,请使用as,

-- Shows the index of the second occurrence.
SELECT CHARINDEX(@FindChar ,@Ssql,CHARINDEX(@FindChar ,LOWER(@Ssql))+1)

答案 1 :(得分:1)

试试这个

Begin Tran
Declare @Ssql As Varchar(100)
Set @Ssql = 'India is mycountry. I love my country and'
Select charindex(' country',lower(@Ssql))+1
RollBack

或尝试将索引起始位置用作

SELECT CHARINDEX('country', @Ssql, 14);

答案 2 :(得分:0)

它会给出第二个字“国家/地区”。指数...

Begin Tran
Declare @Ssql As Varchar(100)
Set @Ssql = 'India is mycountry. I love my country and I am proud of its rich and varied heritage'
Select charindex('country',@Ssql,charindex('country',lower(@Ssql))+1)
RollBack

答案 3 :(得分:0)

恕我直言,你应该更清楚你的要求。抛出2-3个样本字符串并解释欲望输出。

试试这个,

Declare @Ssql As Varchar(200)
Set @Ssql = 'India is mycountry. I love my country and I am proud of its rich and varied heritage'

Declare @x xml='<n>'+REPLACE(@Ssql,' ','</n><n>')+'</n>'
select * from
(
SELECT cast(a.query('./text()') as varchar) val FROM @X.nodes('/n') AS Z(A)
)t4
where val='country'