Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 dynamic sql in function issue

Author  Topic 

iori
Starting Member

20 Posts

Posted - 2008-05-07 : 15:24:07
i want to know if i can use dynamic sql in a function like this:



ALTER FUNCTION [dbo].[udf_GetGradeAvgByNewHireID]
@CourseIDs VARCHAR(MAX),
@NewHireID INT
)
RETURNS INT
AS
BEGIN

/*
1. The CourseIDs passed to this function will be in the form ",1,2,3,"
2. Replace the first and last comma with () so we will have "(1,2,3)"
3. Use this with the IN clause to filter out the right classes for these IDs
*/

DECLARE @SQL VARCHAR(MAX);

--grade average
DECLARE @GradeAvg INT;

--formatting the string to be in the form (1,2,3) from ,1,2,3,4,
SET @CourseIDs = '|' + @CourseIDs + '|';
SET @CourseIDs = REPLACE(@CourseIDs,'|,','(');
SET @CourseIDs = REPLACE(@CourseIDs,',|',')');

SET @SQL = 'SELECT @GradeAvg = AVG(NHC.Class_Grade)
FROM
New_Hires_Classes NHC
INNER JOIN Classes Cls ON NHC.Class_ID=Cls.Class_ID
WHERE Cls.Course_ID IN ' + @CourseIDs +
' AND NHC.New_Hire_ID=@NewHireID';
EXECUTE @SQL

RETURN @GradeAvg



becase when i try to call this function from the query i get this error:


The name 'SELECT @GradeAvg = AVG(NHC.Class_Grade)
FROM
New_Hires_Classes NHC
INNER JOIN Classes Cls ON NHC.Class_ID=Cls.Class_ID
WHERE Cls.Course_ID IN (1,2,3,4,5,6) AND NHC.New_Hire_ID=@NewHireID' is not a valid identifier.

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2008-05-07 : 16:32:55
I'd get rid of the Dynamic SQL, but here is the fix to your issue:
	SET @SQL = 'SELECT @GradeAvg = AVG(NHC.Class_Grade)
FROM
New_Hires_Classes NHC
INNER JOIN Classes Cls ON NHC.Class_ID=Cls.Class_ID
WHERE Cls.Course_ID IN ' + @CourseIDs +
' AND NHC.New_Hire_ID=' + CAST(@NewHireID AS VARCHAR(10)) ;
Go to Top of Page
   

- Advertisement -