SQL替换函数使用CharIndex错误

时间:2016-11-11 03:59:29

标签: sql sql-server sql-server-2008

select REPLACE(comments,substring(comments, 
charindex('statement',comments), LEN(comments)),'') 
from Customer 
where charindex('statement',comments) <>0

我只想更换&#34;声明&#34;来自列注释使用替换功能,但它将记录替换为&#39; &#39;没有&#34;声明&#34;在其中的字符串。

2 个答案:

答案 0 :(得分:2)

请尝试这样,这只会替换注释中的字符串语句:

declare @Customer table(comments nvarchar(max))
insert into @Customer values('this is a statement'), ('statement is this'), ('this')


select case when charindex('statement',comments) <> 0 then REPLACE(comments,substring(comments, charindex('statement',comments), LEN('statement')),'')
else comments end from @Customer 

select * from @Customer

答案 1 :(得分:1)

您应该将其更改为使用大于比较的>

where charindex('statement',comments) > 0

(或)使用like operator

where comments like '%statement%'