SQL Server中通過拆分字串來類比數組

來源:互聯網
上載者:User

數組是非常方便的一種資料結構,但在sql server中卻不被支援,故編寫儲存過程時非常不便,我們可以將多個字串用特定的串連字元串連起來作為參數,需要時再拆開,從而達到類比字串的目的,實現方法是建一個資料表值函式,返回拆分後的情況,如下:

-- =============================================
-- Author:  苟安廷
-- Create date: 2008-1-19
-- Description: 將一個字串拆分到表中
--select * from fSpitStringToTable(';123;223m;323;',';')
-- =============================================
Create FUNCTION [dbo].[fSpitStringToTable]
(
 @List nvarchar(4000), --被拆分的字串
 @SplitChar char   --用於分割的字元
)
RETURNS @Result table (子串 nvarchar(4000),次序 int )
AS
BEGIN
 --聲明用於存放拆分的子串和剩下的字串
 declare @ChildStr nvarchar(4000)
 set @ChildStr=''

 --去掉前置的分隔字元
 while Charindex(@SplitChar,@List,0)=1
  set @List=right(@List,len(@List)-1)
 --去掉後面的分隔字元
 while right(@List,1)=@SplitChar
  set @List=left(@List,len(@List)-1)

 declare @nIndex int
 declare @Order int--次序
 set @Order=1
 while len(@List)>0
 begin
  set @nIndex=Charindex(@SplitChar,@List,0)
  if @nIndex>0
  begin
   set @ChildStr=left(@List,@nIndex-1)
   set @List=right(@List,len(@List)-@nIndex)
  end
  else
  begin
   set @ChildStr=@List
   set @List=''
  end
  if len(@ChildStr)>0
  begin
   insert into @Result(子串,次序) values(@ChildStr,@Order)
   set @Order=@Order+1
  end
 end

 return

END
 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.