愁死我了,(一个函数n参数)
我现在想做一个函数,比如:我想求n个数的和,n是一个不固定的数,这个函数就得写成sum(n1,n2,n3,…………)
怎么写这个函数
------解决方案--------------------一表值函数
select sum(cast(col as int)) from pqs_split( '1,2,3,4,45,645,7567 ', ', ')
------解决方案--------------------declare @s varchar(100)
declare @s1 varchar(100)
declare @i smallint
declare @len smallint
declare @sum smallint
set @sum=0
set @s1= ' '
set @s= '12,32,52,72,19, '
set @len=len(@s)
set @i=0
while @i <=@len
begin
if(substring(@s,@i,1)= ', ')
begin
set @sum=@sum+cast(@s1 as int)
set @s1= ' '
end
else
begin
set @s1=@s1+substring(@s,@i,1)
end
set @i=@i+1
end
print cast(@sum as int)
-------
187
你把這段語句放入函數中,其中,@s為輸入參數
------解决方案--------------------create function sum_data(@s varchar(100))
returns int
as
begin
--declare @s varchar(100)
declare @s1 varchar(100)
declare @i smallint
declare @len smallint
declare @sum smallint
set @sum=0
set @s1= ' '
--set @s= '12,32,52,72,19, '
set @len=len(@s)
set @i=0
while @i <=@len
begin
if(substring(@s,@i,1)= ', ')
begin
set @sum=@sum+cast(@s1 as int)
set @s1= ' '
end
else
begin
set @s1=@s1+substring(@s,@i,1)
end
set @i=@i+1
end
return(@sum)
--print cast(@sum as int)
end
select dbo.sum_data( '12,32,52,72,19, ')
-----------
187
(1 row(s) affected)