Create Function GetSUM(@I Int)
Returns Int
As
Begin
Declare @J Int
Set @J=0
While @I>0
Begin
Select @J=@J+Left(@I,1)
Select @I=Stuff(@I,1,1,'')
End
Return @J
End
GO
Select dbo.GetSUM(12345)
Select dbo.GetSUM(12345678)
GO
Drop Function GetSUM
--Result
/*
15
Declare @I Int
Declare @J Int
Set @I=12345
--Set @I=12345678
Set @J=0
While @I>0
Begin
Select @J=@J+Left(@I,1)
Select @I=Stuff(@I,1,1,'')
End
Select @J
--結果
15
create function f_GetSum(@Num int)
returns int
as
begin
declare @Sum int
set @Sum=0
while @Num!=0
begin
set @Sum=@Sum+@Num%10
set @Num=@Num/10
end
return @Sum
end
go