众所周知,Sql里面居然没有数组类型,让大家每次在存储过程或者触发器中处理数组的时候都很麻烦。我也遇到这样的情况,所以就特意写了两个自定函数,以 方便自己今后在Sql中处理数组。入行不久,懂得不多,贴出来大家探讨一下,希望大家帮我完善 谢谢
通过连个自定义函数来处理Sql中的数组
第一步:数组长度的函数
SQL code
Alter Function arrLen(@string varchar(1000),@SpaceMark Varchar(200))
--@String 眼拆分的字符串 @SpaceMark 分割符
Returns int
As
Begin
Declare @i Int
Set @i = (Len(@string) - Len(Replace(@string,@Spacemark,'')))/Len(@SpaceMark)
Return(@i)
End
第二步:按索引值取数组中的数据
SQL code
Alter Function arrList(@String varchar(8000),@SpaceMark Varchar(8000),@arrStation int)
returns varchar(8000)
As
Begin
Declare @newString varchar(8000)
Declare @ReturnString Varchar(8000)
Set @NewString = @String
Declare @i int
Set @i = 0
if(@arrStation>0 And @arrStation<=Dbo.arrLen(@String,@SpaceMark))
Begin
While(@i<@arrStation)
Begin
Set @NewString = SubString(@NewString,CharIndex(@SpaceMark,@NewString)+1,Len(@NewString))
Set @i = @i + 1
End
End
If(@arrStation<0)
Begin
Set @ReturnString = '上标越界'
End
Else If(@arrStation<dbo.arrLen(@String,@SpaceMark))
Begin
Set @ReturnString = SubString(@NewString,1,CharIndex(@SpaceMark,@NewString)-1)
End
Else if(@arrStation=dbo.arrLen(@String,@SpaceMark))
Begin
Set @ReturnString = @newString
End
Else
Begin
Set @ReturnString = '下标越界'
End
Return(@ReturnString)
End
测试程序:
Declare @a varchar(1000)
Declare @i int
Set @i = 0
Set @a = 'A,B,C,D,E,F,G,H,I'
While(@i <=Dbo.arrLen(@a,','))
Begin
Print Dbo.arrList(@a,',',@i)
Set @i = @i + 1
ENd