我正在使用AdventureWorks(Sql server 2005 express),并希望通过以下SP查看哪个性别的休假时间更长。 SP编译得很好,但在执行时没有显示任何结果
这是sp
create proc GenderLeaveCount
as
begin
declare @gender nchar(1)
declare @leaveHours smallint
declare @totalHoursMale int
declare @totalHoursFemale int
declare genderLeave Cursor
for select Gender , SickLeaveHours
from HumanResources.Employee
where SickLeaveHours is not null and Gender is not null
open genderLeave
fetch next from genderLeave
into @gender,@leaveHours
while @@fetch_status=0
Begin
IF @gender = N'M'
Set @totalHoursMale = @totalHoursMale + @leaveHours
ELSE
Set @totalHoursFemale = @totalHoursFemale + @leaveHours
fetch next from genderLeave
into @gender,@leaveHours
End
close genderLeave
deallocate genderLeave
IF @totalHoursMale > @totalHoursFemale
Select 'Male leave hours are higher:' + cast(@totalHoursMale as varchar(20))as result
IF @totalHoursMale < @totalHoursFemale
Select 'Male leave hours are higher:' + cast(@totalHoursMale as varchar(20))as result
IF @totalHoursMale = @totalHoursFemale
Select 'Male leave hours are higher:' + cast(@totalHoursMale as varchar(20)) as result
end
go
exec GenderLeaveCount
任何人都可以让我知道问题是什么以及如何解决它..
答案 0 :(得分:0)
谢谢Aaron Bertrand ..
:)
.net默认为0所有变量...我想知道为什么MS没有给出sql server变量的默认值..
我初始化它现在有效..有时我在fetch和其他语法中太丢失而且没有注意到这么微小的代码。我正在使用这个sp来演示如何使用带有while语句的游标给我的学生,我知道它不是最好的例子,我也可以使用TVF。 这是改变后的灵魂。
create proc GenderLeaveCount
as
begin
declare @gender nchar(1)
declare @leaveHours smallint
declare @totalHoursMale int
declare @totalHoursFemale int
set @totalHoursMale = 0
set @totalHoursFemale = 0
declare genderLeave Cursor
for select Gender , SickLeaveHours
from HumanResources.Employee
where SickLeaveHours is not null and Gender is not null
open genderLeave
fetch next from genderLeave
into @gender,@leaveHours
while @@fetch_status=0
Begin
IF @gender = N'M'
Set @totalHoursMale = @totalHoursMale + @leaveHours
ELSE
Set @totalHoursFemale = @totalHoursFemale + @leaveHours
fetch next from genderLeave
into @gender,@leaveHours
End
close genderLeave
deallocate genderLeave
IF @totalHoursMale > @totalHoursFemale
Select 'Male leave hours are higher:' + cast(@totalHoursMale as varchar(20))as result
IF @totalHoursMale < @totalHoursFemale
Select 'Female leave hours are higher:' + cast(@totalHoursMale as varchar(20))as result
IF @totalHoursMale = @totalHoursFemale
Select 'Male and Female Leave hours are equal:' + cast(@totalHoursMale as varchar(20)) as result
end
答案 1 :(得分:0)
您可以在查询中使用以下查询而不是游标: 游标的性能低于以下查询:
SELECT CASE
WHEN [M]>[F] THEN 'Male leave hours are higher:' + cast(@M as varchar(20))
WHEN [M]<[F] THEN 'Male leave hours are higher:' + cast(@M as varchar(20))
WHEN [M]=[F] THEN 'Male leave hours are higher:' + cast(@M as varchar(20))
END as result
FROM (SELECT Gender, SUM(SickLeaveHours) AS TotalHours
FROM HumanResources.Employee
WHERE SickLeaveHours is not null and Gender is not null
GROUP BY Gender
)p
PIVOT ( SUM(TotalHours) FOR Gender IN ([M],[F]))pvt