SQL字串分割成若干列

2021-08-25 07:18:03 字數 2475 閱讀 6133

在資料庫程式設計中,很多朋友會碰到分割字串的需求,一般都是分割成一列多行模式,但也有時會需要分割成多列一行的模式,下面我們來看下如何實現這種需求。

首先建立乙個輔助函式,來得到生成多列的sql語句:

create function toarray( @str nvarchar(1000), @sym nvarchar(10) ) returns nvarchar(3000) as begin set @str=rtrim(ltrim(@str)) declare @i int set @i=charindex(@sym,@str collate chinese_prc_cs_as_ws) declare @sql nvarchar(1000) set @sql='select ' declare @ind int=1 while @i>=1 begin set @sql=@sql+''''+left(@str,@i-1)+''' col'+convert(varchar,@ind,10)+',' set @str=substring(@str,@i+1,len(@str)-@i) set @i=charindex(@sym,@str collate chinese_prc_cs_as_ws) set @ind=@ind+1 end if @str<>'' set @sql=@sql+''''+@str+''' col'+convert(varchar,@ind,10)+',' set @sql=left(@sql,len(@sql)-1) return @sql end

關於這個函式,應該不難理解,這裡不再囉嗦

有了生成多列的sql語句,應該如何去利用它呢?我們很自然的想到了臨時表,將資料插入臨時表不就可以用了麼!

但是,臨時表有兩種:本地臨時表和全域性臨時表,本地臨時表的使用是受限制的,它只對當前會話起作用,我們要使用它,只能把要操作的sql語句一起拼接到函式生成的sql中:

declare @sql nvarchar(3000) set @sql=dbo.toarray('11-21','-')+' into #tbarr' set @sql=@sql+' select a.* from tbn a inner join #tbarr b on a.cid=b.col1 and a.bid=b.col2' set @sql=@sql+' drop table #tbarr' exec sp_executesql @sql

但是拼接sql語句是我們應該盡量避免的思路,除非不得以,我們不用。

下面我們看下如何通過常規語句實現這種功能

declare @sql nvarchar(3000) set @sql=dbo.toarray('11-21','-')+' into ##tbarr' exec sp_executesql @sql select a.* from tbn a inner join ##tbarr b on a.cid=b.col1 and a.bid=b.col2 drop table ##tbarr

這樣不可避免的我們使用了全域性表,這也是我們應該盡量避免的程式設計思路,唉沒辦法,總是不能十全十美:(

也許很多朋友不理解,這樣做有什麼意義呢?具體要怎樣的需求才會用到這個方案?

舉個例子:

商品表(product)的結構是這樣的:

主鍵 pid

類別 cid

品牌 bid

現在我們要查詢類別id為11品牌id為21的所有商品,但是我們只得到了類別id+品牌id的字串,那麼應該如何查處對應的商品資訊呢?

看示例**:

create table product ( pid int identity(1,1), cid int, bid int, title varchar(100), dtime datetime default getdate() ) insert into product(cid,bid,title) select 10,20,'aaa' union select 11,21,'bbb' union select 12,22,'ccc' union select 13,23,'ddd' union select 14,24,'eee' go declare @sql nvarchar(3000) set @sql=dbo.toarray('11-21','-')+' into ##tbarr' --如果系統中存在表##tbarr,則刪除 if exists(select name from sysobjects where name='##tbarr'and type='u') begin waitfor delay '00:00:01'--等待1秒鐘 if exists(select name from sysobjects where name='##tbarr'and type='u') drop table ##tbarr end exec sp_executesql @sql select a.* from product a inner join ##tbarr b on a.cid=b.col1 and a.bid=b.col2 drop table ##tbarr

結果如下:

現在這個需求還比較簡單,只有2個id,如果需要判斷多個呢?字串這樣「11-21-32-23」 這樣一來使用這個解決方案的優點就顯而易見了。

split 將字串分割成字串陣列

list name list name.split split 方法用於把乙個字串分割成字串陣列。stringobject.split separator,howmany 引數 描述separator 必需。字串或正規表示式,從該引數指定的地方分割 stringobject。howmany 可選。該...

ORACLE 字串按分隔符分割成多列

參考很多博文,發現都沒有想要的,無奈之下,自己動手,豐衣足食,廢話不多說,一下是需求 資料 小明 小白 小張 小陳 目標 列數根據字串動態生成 構建plsql函式 create or replace function f new rowit in text varchar2,要擷取的字串 fh va...

SQL分割字串

t sql對字串的處理能力比較弱,比如我要迴圈遍歷象1,2,3,4,5這樣的字串,如果用陣列的話,遍歷很簡單,但是t sql不支援陣列,所以處理下來比較麻煩。下邊的函式,實現了象陣列一樣去處理字串。一,用臨時表作為陣列 create function f split c varchar 2000 s...