分割字串–預存程序

來源:互聯網
上載者:User

今天有一個需求需要進行以“;”和“,”為分割符把資料分隔開,然後再插入資料庫裡,用預存程序實現;如字串為:kimhillzhang,20;jinshanzhang,25,現在要以kimhillzhang  20 為一條資料插入資料庫,以jinshanzhang 25為一條資料插入資料庫

name             age

kimhillzhang    20

jinshanzhang   25

預存程序代碼如下:

 

/*
  張金山  2010-5-25
*/
create procedure sp_SplitConent
 @string nvarchar(1000),  -- 要分隔的字串
 @splitchar nvarchar(10) = ';', -- 以“;”為分隔字元
 @splitC  nvarchar(10)=',',  --以“,”為分隔字元
 @tablename nvarchar(50),  -- 存入的表名稱
 @fieldname nvarchar(50)-- 存入的欄位名稱
as -- 將字串分隔開放進表中
declare @l int -- 第一個分隔";"字元的位置
declare @s int -- 第二個分隔";"字元的位置
declare @first int --第一個分隔","字元的位置
declare @last int  --第一個分隔","字元的位置
set @l = 0
set @s = charindex(@splitchar, @string, @l)
while @l <= len(@string) --判斷整串的字元長度
begin
  declare @id nvarchar(50) --用來儲存以“;”分割出來的資料
  declare @value nvarchar(MAX) --用來儲存以“,”分割出來的資料,注意這裡得定義的足夠大,以勉值被截去
  if @s = 0 set @s = len(@string) + 1 -- 如果到最後一個字串那麼第二個分隔字元的位置就是這個字串的長度加一
  set @id = substring(@string, @l, @s - @l) -- 取值
  --實現分割“,”
  set @first = 0
  set @last=charindex(@splitC,@id,@first)
  set @value=''
  while @first <= len(@id)
  begin
    if @last = 0 set @last=len(@id) +1
    if @value = ''
    set @value = ''''+substring(@id,@first,@last-@first)+''','
    else
    set @value = @value + ''''+substring(@id,@first,@last-@first)+''','
    set @first = @last + 1
    set @last = charindex(@splitC, @id, @first) 
  end
 
  set @value = substring(@value,1,len(@value)-1) --去掉最後一個","
    declare @sql nvarchar(1000)
    set @sql = 'insert into ' + @tablename + ' ( '+ @fieldname +' )  values('+ @value +')'
    exec sp_executesql @sql
  set @l = @s + 1
  set @s = charindex(@splitchar, @string, @l) 
end

 

調用 :exec sp_SplitConent 'kimhillzhang,20;jinshanzhang,25',';',',','T_User','username,userage'

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.