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

在存储过程不能使用rand()吗
在存储过程这样写:
select   @Srand   =   cast(cast((rand())   *100000000   as   int)   as   varchar(8))    
提示:
在函数内的   'rand '   中对带副作用的或依赖于时间的运算符的使用无效。

------解决方案--------------------
if object_id( 'vTest ') is not null
drop view vTest
if object_id( 'fnTest ') is not null
drop function fnTest
GO
----创建视图,将rand()函数封装到视图中
create view vTest as select rand() as Srand
GO
----在函数中调用视图
create function fnTest()
returns varchar(10)
as
begin
declare @Srand varchar(10)
select @Srand = cast(cast((select Srand from vTest) *100000000 as int) as varchar(8))
return @Srand
end
GO

drop view vTest
drop function fnTest
------解决方案--------------------
存储过程中可以使用rand,但在函数中不能用,邹老大的书中提示用视图代替
create view v_rand
as
select re=rand()
go

使用时
decalre @re float
select @re=re from v_rand
------解决方案--------------------
SQLSERVER2000规定,函数中不能使用返回不确定值的函数.可以将不确定值函数封装到视图中来间接调用.