【SQLSERVER】處理字段逗號分隔 分別取值問題


之前遇到 數據庫字段保存的數據是 1,2,3 這種格式的數據 要根據逗號分別分隔並取 1、2、3分別對應的中文值。

網上查找一下方法 記錄一下 這些方法:用charindex和for xml path實現批量替換的功能,適用於sql server 2005及以上版本

微軟官方文檔charindex用法:https://docs.microsoft.com/zh-cn/sql/t-sql/functions/charindex-transact-sql?redirectedfrom=MSDN&view=sql-server-2017

微軟官方文檔for xml path用法:https://docs.microsoft.com/zh-cn/sql/t-sql/queries/select-for-clause-transact-sql?redirectedfrom=MSDN&view=sql-server-2017

參考地址:

https://zhidao.baidu.com/question/1046243361841961459.html

最終實現的sql語句如下:

可以根據自己的情況 將table1和table2替換成自己需要的表,字段也要替換成要替換的表。

--測試數據
with table1(id,code) as (
select 1,'001' union all
select 2,'001,002' union all
select 3,'001,002,003'),
table2(code,name) as(
select '001','數學' union all
select '002','體育' union all
select '003','美術')
 
--用charindex和for xml path實現批量替換的功能,適用於sql server 2005及以上版本
select table1.id,stuff((
    select ','+table2.name from table2
    where charindex(','+table2.code+',',','+table1.code+',')>0
    order by table2.code
    for xml path('')
    ),1,1,'') as name 
from table1

下面還有其他的一些方式 ,但是沒有實現我想要的情況 ,結果會按照 比如說字符串內容含有,‘12,1,2’這樣的 其中12會被分隔成1,2和12這樣就不滿足我的要求。

參考地址:https://wenku.baidu.com/view/f418d83258fb770bf78a5569.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM