I'm writing a table-valued function in SQL Server 2000.
I'm trying to declare and populate a table variable within the function, and then use that table in a JOIN statement, also inside the function.
Is this possible? Here is the code I have now:
BEGIN
DECLARE @dateTable TABLE
(
[Date] datetime
)
DECLARE @cDate datetime
SET @cDate = @StartDate
WHILE @cDate <= @EndDate
BEGIN
INSERT INTO @dateTable ([Date]) VALUES (@cDate)
SET @cDate = DATEADD(dd, 1, @cDate)
END
INSERT INTO @table
SELECT TOP 100 PERCENT Departments.ID AS [Department.ID], Departments.Name AS [Department.Name], Shifts.ID AS [Shift.ID], Shifts.Name AS [Shift.Name],
Shifts.StartTime AS [Shift.StartTime], Shifts.EndTime AS [Shift.EndTime], ShiftDays.DayOfWeek AS [ShiftDay.DayOfWeek],
Workdays.ID AS [WorkDay.ID], Workdays.Budget AS [WorkDay.Budget], Workdays.HoursNeeded AS [WorkDay.HoursNeeded],
Workdays.[Date] AS [WorkDay.Date]
FROM ShiftDays INNER JOIN
Shifts ON ShiftDays.ShiftID = Shifts.ID INNER JOIN
Departments ON Shifts.DepartmentID = Departments.ID LEFT OUTER JOIN
Workdays ON Departments.ID = Workdays.DepartmentID AND ShiftDays.DayOfWeek = Workdays.DayOfWeek RIGHT OUTER JOIN
@dateTable ON Workdays.[Date] = @dateTable.[Date]
WHERE (Departments.EmployerID = @EmployerID)
RETURN
END
However, I get the error "ADO error: Must declare the variable '@dateTable'" ... even though it is clearly already declared and populated.