數組是非常方便的一種資料結構,但在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