Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating function using newID()

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
like image 652
WingMan20-10 Avatar asked Feb 02 '10 18:02

WingMan20-10


People also ask

What does newid () do in SQL?

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).

How do I use Newid?

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.

What does ORDER BY newid () do?

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.


2 Answers

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())
like image 74
AdaTheDev Avatar answered Oct 31 '22 12:10

AdaTheDev


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.

like image 33
Andrew Avatar answered Oct 31 '22 11:10

Andrew