views:

248

answers:

3

Hi folks:

I try to implement the following link with a scalar-valued function, the SQL Server 2000 return an error msg: Invalid use of 'newid' within a function.

http://www.bennadel.com/blog/310-Ask-Ben-Getting-A-Random-Date-From-A-Date-Range-In-SQL.htm

Is there any way to get around this?

+3  A: 

In SQL 2000 you couldn't use non-deterministic functions inside other functions.

The best way of doing this is to use a subquery inside your outer query. It will perform better than a scalar function anyway, as per my blog at: http://msmvps.com/blogs/robfarley/archive/2009/12/05/dangers-of-begin-and-end.aspx

Rob Farley
Functions are not inherently bad, just abused. Multi-valued table valued ones, or scalars with table access (in SELECT clause, say) is what people misuse. But wrapping a calculation, for example, can only be a good thing. Speed is not everything especially at the expense of maintenance
gbn
Hi gbn. Sorry, but even if you have just wrapped a calculation into a function, if it's a scalar function or multi-line table-valued one, SQL will execute it in a new context, which becomes very costly. You should always strive to make simplifiable functions so that the Query Optimizer can do its job better. A multi-valued table-valued function is just fine, so long as you haven't used BEGIN/END (which makes it procedural, not simplifiable).
Rob Farley
A: 

The only way i have found to do this is by creating a view that selects the NEWID() value, and then use this view inside the function.

astander
A: 

Why not pass in NEW_ID() as a parameter all the time? It's overkill to use a view, IMHO

ALTER FUNCTION dbo.MyFunc (
    @param1 int, 
    @param2 datetime,
    @GUID uniqueidentifier
)
RETURNS int
AS
....



SELECT dbo.MyFunc (1, '20091221', NEWID())
gbn