2 回答

TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超13個贊
substring參數(shù)使用不正確,很明顯,錯誤也在提示你這個原因!
substring一共要三個參數(shù),第一個為要截的字符,第二個為字符串截取的起始位置,最后一個為要截取的長度!
很明顯你要截取的字符串是@content,
起始位置為@spaceindex1+len(@text1),
長度為@spaceindex2-@spaceindex1-len(@text1)
這幾個值你寫的都是正確的,但我們必須要考慮一些意外情況!
varchar與nvarchar兩者之間的區(qū)別!還有就是查找不到的情況!比如你輸入的錯了一個字符,那么就會導(dǎo)致@spaceindex1與@spaceindex2都為0第一個式子還好說,而第二個,也就是說長度會變?yōu)樨?fù)值,而substring就會報錯!
所以我們不妨先測試一下@spaceindex2的值,若為0時,則直接讓其等于len(@content),這樣如果查不到由直接返回整個字串,當(dāng)然如果是@spaceindex1不為0時,還可以照樣截取.
另一種情況也是你程序中常出現(xiàn)的錯誤!
set @spaceindex2=charindex(@text2,@content)如果反過來了,也是得到的負(fù)值的.好在charindex支持第三個參數(shù)!
set @spaceindex2=charindex(@text2,@content,@spaceindex1+1)
這樣做的目的是保證@spaceindex2大于@spaceindex1,否則照出現(xiàn)錯誤!為了杜絕重復(fù)引起的錯誤,最好是
set @spaceindex2=charindex(@text2,@content,@spaceindex1+1+len(@text1))
這樣保證了@spaceindex2-len(@text1)也大于@spaceindex1
最后的那個varchar與nvarchar兩者的區(qū)別,建議你如果處理有中文最好用nvarchar,因?yàn)檫@兩個在統(tǒng)計長度是不至于出錯的!
我想你最終的程序,應(yīng)該是好修改的吧?

TA貢獻(xiàn)1852條經(jīng)驗(yàn) 獲得超7個贊
先做個判斷@content 是否含有@text1,@text2
如果沒有直接返回''
if @spaceindex1=0 or @spaceindex2=0
begin
@return=''
end
else
begin
set @return=substring(@content,@spaceindex1+len(@text1),@spaceindex2-@spaceindex1-len(@text1))
end
return @return
end
- 2 回答
- 0 關(guān)注
- 590 瀏覽
添加回答
舉報