日期:2014-05-19  浏览次数:20438 次

大家帮写一个自定义函数吧。谢谢了。
大家帮写一个自定义函数吧。谢谢了。
功能是:
对于一个字符串,有可能是下列形式:
下面字符串结果要返回3,即一共3页
1,4,67         (表示第一页,第四页,第67页)

下面字符串要返回7,即一共7页
1,5-9,3         (表示第一页,第五页到第九页,第三页)

下面字符串要返回4,即一共4页
3,5-7           (表示第三页,第五页到第七页)

要求函数的参数就是字符串,返回值就是数字,如何写呀,谢谢大家


------解决方案--------------------

--建立函数
create function fn_Num(
@str varchar(500)
)
returns int
as
begin
declare @r int
declare @x varchar(50)
declare @i int
declare @j int

set @r=0
while charindex( ', ',@str)> 0
begin
set @x=left(@str,charindex( ', ',@str)-1)
set @str=stuff(@str,1,charindex( ', ',@str), ' ')
if charindex( '- ',@x)> 0
begin
set @i=left(@x,charindex( '- ',@x)-1)
set @j=stuff(@x,1,charindex( '- ',@x), ' ')
set @r=@r+@j-@i+1
end
else
set @r=@r++1
end
if @str <> ' '
if charindex( '- ',@str)> 0
begin
set @i=left(@str,charindex( '- ',@str)-1)
set @j=stuff(@str,1,charindex( '- ',@str), ' ')
set @r=@r+@j-@i+1
end
else
set @r=@r++1
return @r
end

go

--测试
select dbo.fn_Num( '1,4,67 ') as [1,4,67],
dbo.fn_Num( '1,5-9,3 ') as [1,5-9,3],
dbo.fn_Num( '3,5-7 ') as [3,5-7],
dbo.fn_Num( '1-100,190 ') as [1-100,190]

--结果
1,4,67 1,5-9,3 3,5-7 1-100,190
----------- ----------- ----------- -----------
3 7 4 101

(所影响的行数为 1 行)

------解决方案--------------------
create function fun_fun(@s varchar(100))
returns int
as
begin
declare @i int
declare @t table(a varchar(10),b int)

set @s=@s+ ', '
while charindex( ', ',@s)> 0
begin
insert @t(a) select left(@s,charindex( ', ',@s)-1)
set @s=right(@s,len(@s)-charindex( ', ',@s))
end
select @i =sum(b) from (select a,b=case when charindex( '- ',a)> 0 then -cast(left(a,charindex( '- ',a)-1) as int) + cast(right(a,len(a)-charindex( '- ',a)) as int)+1 else 1 end from @t )tt
return @i
end

go

select dbo.fun_fun( '1,5-9,3 ')
------解决方案--------------------
借用两位大侠的思想:
--建立函数
create function fn_Num(@str varchar(500))
returns int
as
begin
declare @r int
declare @x varchar(50)
declare @i int
declare @j int

set @r=0
set @str=@str+ ', ' --给字符串加上一个逗号可以不用另外判断
while charindex( ', ',@str)> 0
begin
set @x=left(@str,charindex( ', ',@str)-1)
set @str=stuff(@str,1,charindex( ', ',@str), ' ')
if charindex( '- ',@x)> 0
begin
set @i=left(@x,charindex( '- ',@x)-1)
set @j=stuff(@x,1,charindex( '- ',@x), ' ')
set @r=@r+@j-@i+1
end
else
set @r=@r++1
end
return @r
end

go

--测试
select dbo.fn_Num( '1,4,67 ') as [1,4,67],
dbo.