Home [SQL] 操作字串 (取代 Replace、Stuff)
Post
Cancel

[SQL] 操作字串 (取代 Replace、Stuff)

Replace

將指定字串值的所有相符項目取代成另一個字串值。

語法

1
REPLACE ( string_expression , string_pattern , string_replacement )
1
select replace('ooxxooxx','x','R') --ooRRooRR

範例

1
2
--將商品中的「電腦」換成「PC」
select replace(商品名稱, '電腦', 'PC') "商品名稱" from 商品清單

執行結果:

1
2
3
4
5
6
7
8
9
10
11
商品名稱
桌上型PC
筆記型PC
17吋螢幕
19吋螢幕
15吋液晶螢幕
數位相機
印表機
掃描器
HUB
網路卡

Stuff

STUFF 函數會將字串插入另一個字串。 它會在第一個字串的開始位置刪除指定長度的字元,然後將第二個字串插入第一個字串的開始位置。

語法

1
STUFF ( character_expression , start , length , replace_with_expression )

範例

1
2
3
--stuff(str1, i, n, str2)
--將字串str1從第i個字元開始刪掉n個字元,然後位置插入字串str2
select stuff('ooiixx',3,2,'RRR') --ooRRRxx

執行結果

1
ooRRRxx

MSDN - STUFF (Transact-SQL)
MSDN - REPLACE (Transact-SQL)

This post is licensed under CC BY 4.0 by the author.