最近遇到一個case, 需要填入多數值並作查詢
for example:abcde, bcdef ,cdefg...
但作為參數傳進stored procedures
exec myproc test @ts = 'abcde, bcdef'
始終都無法成功...
解決方式:
1. 用原始方法,將參數@ts 分為 @ts0, @ts1,@ts2...
但若遇到一次輸入10個以上, 就會顯得很笨拙
2. 新方法,用T-SQLq取代
Declare @ ts varchar(50) set @ ts = 'abcde,bcdef' select * from test where charindex (ts,@ts) | |
使用 CHARINDEX 主要是找出符合比較值,傳回在比較值的顯示位置(如果有就會大於0)
可自行搭配function 或 stored procedures
希望能解答有遇到類似問題的同好們
測試function的結果
回覆刪除發現 where charindex (ts,@ts) > 0 和 where charindex (@ts,ts) > 0 是會有不一樣
前端若重新拆拼字串的話, where charindex (ts,@ts) > 0 才會有資料,因為是從前端傳進參數的關係,先判別ts的所在位置,再依據@ts的參數值
今天重新試了一下,若是要篩選出符合兩個不同的值
回覆刪除Declare
@ts varchar(50)='abcd'
@us varchar(50)='efgh'
可改為where charindex (ts,@ts) <> 0 and charindex (us,@us) <> 0
P.S. 這會比like '%abcd%' or '%efgh%' 更有效率,但
前提是需加上INDEX。