【发布时间】:2016-01-04 23:30:49
【问题描述】:
如何在 SQL Server 2012 中创建一个存储过程,返回一个运行在 2 个月之间的课程列表?
我写过这样的代码:
create procedure final_RTrainerqualification
(@TrainerID char(10),
@Coursecode char(4) OUTPUT,
@qualcode nvarchar(30),
@coursedate datetime output)
DECLARE @MinDate DATE = '20160401',
@MaxDate DATE = '20160601';
SELECT coursedate
FROM dbo.RTrainerqualification
WHERE coursedate >= @MinDate
AND coursedate < @MaxDate;`
它应该返回在提到的这两个日期之间运行的课程列表,但我是存储过程的新手,所以我的问题是如何将课程日期分配给课程并使其返回列表?
Edit-使用 T-SQL 重新创建代码
@Coursecount smallint
declare @Coursedatebeg datetime, @Coursedateend datetime, @CourseCode char(4),@TrainerID char(10);
select @Coursedatebeg = '2015-04-20'
select @Coursedateend = '2015-06-20';
while @Coursedatebeg <= @Coursedateend
begin
select @CourseCode = @Coursedateend;
select @Coursecount = count(*) from RCourseInstance
where CourseCode between 'R222' and 'R224';
if @CourseCount <> 0
begin
Print 'Courses running between April and June 2015 ' ;
select Coursedate,CourseCode from RCourseInstance as t
inner join Coursedate as d on t.Coursedate = d.Coursedate
inner join CourseCode as c on c.CourseCode = t.CourseCode
where CourseCode between 'R222' and 'R224';
end
else
print 'No courses are running between these dates ' ;
set @Coursedatebeg = @Coursedatebeg + 2;
end
It is returning the print statement but also declaring that invalid object name Coursedate 我在这里做错了什么?
【问题讨论】:
-
dbo.RTrainerqualification 是唯一涉及的表吗?其他表中是否有您需要数据的列?无需将数据分配给输出变量,您只需将 select 语句中所需的数据包含在存储过程中即可。包括 Min 和 Max 日期作为参数(不是变量)。
-
您的问题不清楚。你想分配的课程是什么?如果您的意思是您的 OUTPUT 参数,那么 SELECT 只会将一行(最后一行)的值分配给变量(除非您使用 ORDER BY 指定 TOP 1)。要返回完整列表,您只需在 SELECT 中包含您需要的所有列。
-
我需要返回未来 2 个月内运行的课程列表,因此日期介于 2016 年 4 月 1 日和 2016 年 6 月 1 日之间,应该返回这几个月之间教授的课程。但它显示所有日期而没有任何课程信息。我已经声明了课程代码,但是是因为它没有被分配吗?
标签: sql stored-procedures sql-server-2012