这种语法有什么问题?
Declare @comparisongroup int;
...
Insert Into @universitytemp Case @comparisongroup
When -1 Then Select * From dbo.University;
When -2 Then Select * From dbo.University Where SubDivisionName = @group;
When -3 Then Select * From dbo.University Where ConferenceName = @group;
Else Select * From dbo.GroupUniversity Where GroupID = CONVERT(int, @group);
End;
这不起作用
Declare @comparisongroup int;
...
Case @comparisongroup
When -1 Then Insert Into @universitytemp Select * From dbo.University
When -2 Then Insert Into @universitytemp Select * From dbo.University Where SubDivisionName = @group
When -3 Then Insert Into @universitytemp Select * From dbo.University Where ConferenceName = @group
Else Insert Into @universitytemp Select * From dbo.GroupUniversity Where GroupID = CONVERT(int, @group)
End;
这两个都没有:
Declare @comparisongroup int;
...
Case
When @comparisongroup = -1 Then Insert Into @universitytemp Select * From dbo.University;
When @comparisongroup = -2 Then Insert Into @universitytemp Select * From dbo.University Where SubDivisionName = @group
When @comparisongroup = -3 Then Insert Into @universitytemp Select * From dbo.University Where ConferenceName = @group
Else Insert Into @universitytemp Select * From dbo.GroupUniversity Where GroupID = CONVERT(int, @group)
End;
我收到错误Incorrect syntax near the keyword 'When', 'Else', and 'End'
答案 0 :(得分:2)
那是因为CASE
是表达式,它返回值。单个值。不是结果集。
您可以尝试:
SELECT
* --todo - explicit column list
FROM
dbo.University u
WHERE
@comparisongroup = -1 OR
(@comparisongroup = -2 AND SubDivisionName = @Group) OR
(@comparisongroup = -3 AND ConferenceName = @Group)
UNION ALL
SELECT
* --todo - explicit column list
FROM
dbo.GroupUniversity
WHERE GroupID = CONVERT(int, @group) AND NOT @ComparisonGroup in (-1,-2,-3);
即。根本不使用CASE
表达式。作为一个风格点,我也可能将@group
分成两个参数/变量 - 一个名称中包含“name”,并且继续为(varchar?),另一个是 int
,仅用于GroupID
比较。