Suppose I want to get student summaries from a two tables: student, grade:
CREATE PROCEDURE prc_get_student_grade_summaries
@studentIds [Integer_udtt] READONLY
AS
BEGIN
SELECT Name,
func_GetGradeAForStudent()
FROM tbl_student AS tS
INNER JOIN
@studentIds AS tSI
ON tS.Id = tSI.studentId
Integer udtt is defined as this:
CREATE TYPE [Integer_udtt] AS TABLE (
[Id] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC));
func_GetGradeAForStudent is something like select COUNT(*) from student where studentId = id AND grade = 1 — 1: A
The result I want is list of summary:
StudentId Number of A
101 5
102 4
103 2
What is the correct way to pass in the studentId from @studentIds to the func_GetGradeAForStudent?
You can’t pass table-value parameters to UDF’s:
MSDN:
Since these are just a list of student Ids, one possibility would be to pass those Ids as a comma-separeted list of ids and use a split function to recreate a table from the comma-separeted list. There’s a ton of examples here on SO and elsewhere where you can find sample implementation of a split function.
Or even better, do everything inside your proc. I don’t really see the need for that function if all is doing is a
select count(*)...You should be able to do everything inline, perhaps using a subselect as so:UPDATE
Sample split function that takes a comma-separated list and returns a table:
And you call it like this:
select * from fnSplit(@CommaSeparetedList,',');