如何返回SQL Server 2012 Management Studio中2个月之间的课程列表



如何在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;`

它应该返回在上述两个日期之间运行的课程列表,但我是存储过程的新手,所以我的问题是如何为课程分配课程日期并使其返回列表?

编辑-使用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

它返回print语句,但同时声明无效的对象名Coursedate我在这里做错了什么?

首先,使用ISO日期字符串来避免区域设置问题。您只是在SELECT中返回课程日期。如果您想要更多信息,如课程代码,请将其添加到SELECT中。即

DECLARE @MinDate DATE = '2016-04-01',
@MaxDate DATE = '2016-06-01'
SELECT coursedate, coursecode, *
FROM dbo.RTrainerqualification
WHERE coursedate >= @MinDate
AND coursedate < @MaxDate;

OUTPUT变量不是必需的——当您想要返回单个值而不是列表时,这些变量是必需的。

这是SQL的基本内容,所以我强烈建议您阅读一下。这里有一个简单的存储过程教程。

最新更新