create function fun(@a int, @b int)
returns int
as
begin
declare @k int,@x int,@i real
select @k=2,@x=@a
while @x<=@b
begin
set @i=sqrt(@x)
while @k<=@i
begin
if @x/@k=0
break
else set @k=@k+1
end
if @k>@i
return @x
else
set @x=@x+1
set @k=2
end
if @a > @b
return '不存在'
endselect master.dbo.fun(9,12)执行查询时显示
服务器: 消息 156,级别 15,状态 1,过程 fun,行 31
在关键字 'select' 附近有语法错误。请问我如何写查询语句调用此函数啊得到结果啊?
请各位帮我看下,,十分感谢!
--你的函数建立就报错……
create function fun(@a int, @b int)
returns int
as
begin
declare @k int,@x int,@i real
select @k=2,@x=@a
while @x <=@b
begin
set @i=sqrt(@x)
while @k <=@i
begin
if @x/@k=0
break
else set @k=@k+1
end
if @k>@i
return @x
else
set @x=@x+1
set @k=2
end
if @a > @b
return '不存在' end /*
服务器: 消息 455,级别 16,状态 2,过程 fun,行 65535
函数中最后一条语句必须是返回语句。*/
returns int
as
begin
declare @k int,@x int,@i int
select @k=2,@x=@a
while @x <=@b
begin
set @i=floor(sqrt(@x))
while @k <=@i
begin
if @x%@k=0 break
set @k=@k+1
end if @k>@i return @x set @x=@x+1
set @k=2
end return -1
end select dbo.fun(9,12)
/*
-----------
11(1 行受影响)
*/
drop function fun
create function fun(@a int, @b int)
returns int
as
begin
declare @k int,@x int,@i real
select @k=2,@x=@a
while @x <=@b
begin
set @i=sqrt(@x)
while @k <=@i
begin
if @x/@k=0
break
else set @k=@k+1
end
if @k>@i
return @x
else
set @x=@x+1
set @k=2
end
if @a > @b
begin
return '不存在'
end
return '存在'
end select dbo.fun(9,12)
/*
-----------
9(所影响的行数为 1 行)
*/
returns int
as
begin
declare @k int,@x int,@i real
select @k=2,@x=@a
while @x <=@b
begin
set @i=sqrt(@x)
while @k <=@i
begin
if @x/@k=0
break
else set @k=@k+1
end
if @k>@i
return @x
break -- 此处漏了break退出循环 else
set @x=@x+1
set @k=2
end
if @a > @b
return '不存在'
end select master.dbo.fun(9,12)
还是不知道怎么输出结果
算法在c++中可以执行得到结果
if object_id('fun','fn') is not null
drop function fun
go
--创建函数
create function fun(@a int, @b int)
returns int
as
begin
declare @k int,@x int,@i int
select @k=2,@x=@a
while @x <=@b
begin
set @i=floor(sqrt(@x))
while @k <=@i
begin
if @x%@k=0 break
set @k=@k+1
end if @k>@i return @x set @x=@x+1
set @k=2
end return -1 --表示没有满足条件的数。注意不能写成:return '不存在',因为已经这个函数必须返回int.
end
go
--输出结果:
select dbo.fun(9,12)
/*
-----------
11
*/
select dbo.fun(6,12)
/*
-----------
7
*/
select dbo.fun(2,12)
/*
-----------
2
*/
select dbo.fun(9,10)
/*
-----------
-1
*/--删除函数
drop function fun
我用的sqlsever2000的还是显示:
服务器: 消息 156,级别 15,状态 1,过程 fun,行 25
在关键字 'select' 附近有语法错误。
create function fun(@a int, @b int)
returns int
as
begin
declare @k int,@x int,@i int
if(@a>@b)
begin
set @x=@b
set @b=@a
set @a=@x
end
select @k=2,@x=@a
while @x <=@b
begin
set @i=sqrt(@x)
while @k <=@i
begin
if @x%@k=0
break
else set @k=@k+1
end
if @k>@i
begin
return @x
end
set @x=@x+1
set @k=2
end
return -1--'不存在'
end --select dbo.fun(12,19)
--13
--select dbo.fun(19,12)
--13
在选中
select dbo.fun(15,20) 语句执行查询
这样才能的到结果
我第一次用sql语句写这个
碰到这么多问题
总算明白了