views:

650

answers:

1

Is it possible to create and use a user defined function in a report query?

Something like this:

if OBJECT_ID('userFunc', 'TF') is not null drop function userFunc
go

create function userFunc(@id int)
returns @tbl table
([id] int)
begin
insert into @tbl (id) values(@id)
return
end
go

select * from userFunc(1)

if OBJECT_ID('userFunc', 'TF') is not null drop function userFunc

When i run this query in SQL Server 2008 Management Studio it returns me 'id':1, but when i put this query into Reporting Query designer - i get the next error:

TITLE: Microsoft Report Designer

An error occurred while the query design method was being saved. Incorrect syntax near 'go'.

'CREATE FUNCTION' must be the first statement in a query batch.

Incorrect syntax near 'go'.

Incorrect syntax near 'userFunc'.

Any suggestions? How to create and use udf in Reporting Services queries?

+1  A: 

"GO" will only be recognised by SQL tools: not the DB engine nor SSRS parser

This might if you really want to

EXEC 'if OBJECT_ID(''userFunc'') is not null drop function userFunc'
EXEC 'create function userFunc(@id int)
returns @tbl table
([id] int)
begin
insert into @tbl (id) values(@id)
return
end'
select * from userFunc(1)

However, you'll need ddl_admin or db_owner to run it.

Have you considered a CTE or derived table? A table valued udf like this can be replaced by a CTE

gbn
Thank you very much for the help, it is exactly what i am looking for. This udf was created only like example, real udf is much more complicated.
Vitaly