I'm using NEWID() inside a function. this is my function:
CREATE FUNCTION dbo.myFunc (@newid NVARCHAR(50))
RETURNS int
AS BEGIN
declare @rndValue int
set @rndValue = (SELECT top 1 * FROM #temp ORDER BY lower(@newid))
RETURN @rndValue
END
i have #temp with values: '1','2','3' i want to random from this table using this function. i called this function like this:
dbo.myFunc (NEWID())
but i'm getting every time the same value ('1')
where is my error?

The function isn't using NEWID(). It's using the value of a string parameter named
@newidIf you want to select a random row, use
ORDER BY NEWID(). This generates a new non-sequential GUID for every row and orders the rows by it, effectively producing a random ordering, eg :The original query orders rows by a constant and thus has no effect. It's no different than using
If you check the query's execution plan you'll see there's no SORT operation. The query optimizer simply removes the ineffective
ORDER BYclause.Finally, NEWID() produces a GUID, not a string. That's a 128-bit binary value. Using
LOWER()serves no purpose