|
Posted by Erland Sommarskog on 04/21/07 16:05
SQL Server (alderran666@gmail.com) writes:
> I am writing a function which will take two parameters. One the field
> to be returned from a table and second parameter is the ID of the
> record to be returned.
>
> Problem is it's not returning the value of the field specified in the
> parameter but instead returns the parameter itself. Is there a
> function that will get the parameter to be evaluted first?
>
> ALTER FUNCTION [dbo].[getScholarYearData]
> (
> -- Add the parameters for the function here
> @FieldName varchar(50), @ScholarID int
> )
> RETURNS varchar(255)
> AS
> BEGIN
> -- Declare the return variable here
> DECLARE @ResultVar varchar(255)
>
> -- Add the T-SQL statements to compute the return value here
> SELECT @ResultVar=EXECUTE(@FieldName)
This does not even compile.
The fact that you want to pass a parameter for the column name indicates
that you have a poor table design. Columns should represent unique
attributes, and normally it's not meaningful to sometimes return one
column and sometimes another.
Nevertheless, you can use the CASE expression:
@ResultVar = CASE @FieldName
WHEN 'thiscol' THEN thiscol
WHEN 'thatcol' THEN thatcol
WHEN 'thatothercol' THEN thatothercol
END
--
Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx
Navigation:
[Reply to this message]
|