I’m using SQL Server 2005, and want a user defined function to implement the following:
Parameter: @SQL varchar(max)
execute 'select count(1) from (' + @sql + ')'
and return the result as integer.
This is the dummy code >>
ALTER FUNCTION [dbo].udf_GetCountFromSQL ( @SQL VARCHAR(MAX) )
RETURNS INT
AS
BEGIN
DECLARE @returnValue INT
SET @SQL = 'SELECT COUNT(1) FROM (' + @SQL + ')'
EXEC @returnValue= @SQL
RETURN @returnValue ;
END
@SQL here is dynamic sql, not stored procedure name, so it doesn’t work.
Wait to be helped out, thanks in advance.
Elaine
You can’t execute dynamic SQL in a user defined function.
You’d need to change it to a stored procedure and use sp_executesql to get the count into a variable – you can then pass the count out as an OUTPUT parameter (or RETURN value if you want).
Then call like this:
However, you need to be very careful as you’re opening yourself up to SQL injection attacks (what if @SQL contains something dodgy?).