On Thu, 31 Jul 2008 09:54:03 -0700 (PDT),
jduhler@hotmail.com wrote:
(snip)
Quote:
>I have tried using a function such as:
>
>CREATE FUNCTION myfunction (@MYVAR int)
> RETURNS VARCHAR(2000)
>AS
>BEGIN
> RETURN 'SELECT A FROM B WHERE C=' + @MYVAR + ' FIELDVALUE'
>END
Hi JD,
You are telling SQL Server to return a string. SQL Server will do that,
without bothering to see if that string happens to be a valid query.
If you want to return the result of the query, you'll have to execute
it, store the result, and than return the result.
CREATE FUNCTION dbo.myfunction (@MYVAR int)
RETURNS VARCHAR(2000)
AS
BEGIN;
DECLARE @Res vanrchar(2000);
SET @Res = (SELECT A FROM B WHERE C = @MYVAR);
RETURN @Res;
END;
Note however that encapsulating reused code in seperate functions may
save on maintenance, but you pay the price in performance. SQL Server
can no longer optimize the queries as good as it would otherwise do.
Take for instance this query:
SELECT Col1, Col2
FROM SomeTable
WHERE SomeColumn = @SomeValue;
You can consider to "refactor" this to use two functions, one to fetch
the Col1 value and one to fetch the Col2 value, like this:
SELECT dbo.GetCol1FromTable(@SomeValue) AS Col1,
dbo.GetCol2FromTable(@SomeValue) AS Col2;
But the result will be that SQL Server has to access the same table
twice, reading the same row both times. You have just doubled execution
time!
And it gets even worse if joins are involved.
--
Hugo Kornelis, SQL Server MVP
My SQL Server blog:
http://sqlblog.com/blogs/hugo_kornelis