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索引。
我该怎么做?
请帮忙。
答案 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)
试试这个,
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'