亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

關于該如何定義SQL用戶函數取單元格內值?

關于該如何定義SQL用戶函數取單元格內值?

FFIVE 2021-12-04 18:14:32
在SQL Server2005中定義了一個用戶函數,想達到在單元格中取出段落1與段落2之間的文字效果。具體如下: Create function dbo.mid (@content varchar(1000),@text1 varchar(30),@text2 varchar(30)) --@content is one paragraph where I wanna search target words. --@text1 is the words before target words. --@text2 is the words after target words. returns varchar(30) as begin declare @spaceindex1 int,@spaceindex2 int,@return varchar(30) set @spaceindex1=charindex(@text1,@content) set @spaceindex2=charindex(@text2,@content) set @return=substring(@content,@spaceindex1+len(@text1),@spaceindex2-@spaceindex1-len(@text1)) return @return end 定義完成后,使用該用戶定義函數: Select dbo.mid ('baidu','b','u') 則能夠返回 aid 但是用在對應的表中時,例如: select dbo.mid (tab1,'我的名字是:',',請多多關照.') from table1 會報 "消息 536,級別 16,狀態 5,第 1行 傳遞到 SUBSTRING 函數的長度參數無效." 試過把substring中的長度參數從@spaceindex2-@spaceindex1-len(@text1)改為@spaceindex2-@spaceindex1-convert(varchar(20),len(@text1)) 依然上述錯誤 試過把每個參數都改為varchar(1000),依然報錯。 我現在只能把substring中的長度參數改為@spaceindex2-@spaceindex1 這樣不會報錯了。但是這樣的話我需要在用到的時候手動刪除每個后面的多余字符。 請高手幫忙,如何修改可以到達所需效果,謝謝!
查看完整描述

1 回答

?
茅侃侃

TA貢獻1842條經驗 獲得超21個贊

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



查看完整回答
反對 回復 2021-12-07
  • 1 回答
  • 0 關注
  • 371 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號