sql在函数内对带副作用的运算符✀rand✀的使用无效。如果我想在自定义函数使用随机数怎么办

2025-04-27 03:52:59
推荐回答(1个)
回答1:

--1.可以先建立一个视图,然后函数中调用
Create View v
As
    Select RAND() As A
    
Create Function fn()
Returns Numeric(38,8)
As
Begin
    Declare @RSt Numeric(38,8) 
    Select @RSt=A From v
    Return @RSt
End
 
--2.mssql2008可以用这个函数
Create Function fn()
Returns Int
As
Begin
    Return CRYPT_GEN_RANDOM(4) 
End