I keep getting this error: Any Ideas?
Invalid use of side-effecting or time-dependent operator in 'newid' within a function.
I am working with MS-SQL Server 2005
. Here is the T-SQL
statement:
Create Function [dbo].[GetNewNumber]( )
RETURNS int
AS
BEGIN
Declare @code int
set @code = (SELECT CAST(CAST(newid() AS binary(3)) AS int) )
RETURN (@code)
END
The NEWID() function in SQL Server returns a unique id or a random value. For example, the query SELECT NEWID() will always return a unique value (yes always).
Using NEWID in a CREATE TABLE statement. The following example creates the cust table with a uniqueidentifier data type, and uses NEWID to fill the table with a default value. In assigning the default value of NEWID() , each new and existing row has a unique value for the CustomerID column.
SQL NEWID() function can be used to sort records in random order in SQL Server. SQL Server NewId() generates a random GUID or unique identifier which can be used to return randomized rows from a SELECT query.
You can't use NEWID() within a function.
A usual workaround (in my experience, it's more been the need for GETDATE()) is to have to pass it in:
Create Function [dbo].[GetNewNumber](@newid UNIQUEIDENTIFIER )
RETURNS int
AS
BEGIN
Declare @code int
set @code = (SELECT CAST(CAST(@newid AS binary(3)) AS int) )
RETURN (@code)
END
And call it like:
SELECT dbo.GetNewNumber(NEWID())
The function will not let you use the NewID, but this can be worked around.
Create View vwGetNewNumber
as
Select Cast(Cast(newid() AS binary(3)) AS int) as NextID
Create Function [dbo].[GetNewNumber] ( ) RETURNS int
AS
BEGIN
Declare @code int
Select top 1 @code=NextID from vwGetNewNumber
RETURN (@code)
END
Then you can use select dbo.[GetNewNumber]()
as planned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With