如何修复语法,我想只根据用户输入执行一个select语句,即@id
Create Procedure employee
@id int,
@year int
AS
SELECT
CASE
WHEN @id = 1
THEN (select a.name, b.roles
from employee a
inner join department b on a.id = b.id
where b.years in (@year)
or b.roles is not null)
ELSE
CASE
WHEN @id = 2
THEN (select a.name, b.dayoff
from employee a
inner join department b on a.id = b.id
where b.years in (@year)
or b.dayoff is not null)
答案 0 :(得分:2)
据推测,您需要if
:
Create Procedure employee (
@id int,
@year int
)
AS
BEGIN
IF @id = 1
BEGIN
select a.name, b.roles
from employee a join
department b
ON a.id = b.id
where b.years IN (@year) OR b.roles IS NOT NULL ) ;
END
ELSE if @id = 2
BEGIN
select a.name, b.dayoff
from employee a join
department b
ON a.id = b.id
where b.years IN (@year) OR b.dayoff IS NOT NULL ) ;
END
END;
我不确定您为何in
使用@year
;这仅在@year
中有一个值时才有效。
答案 1 :(得分:1)
更改以下行
SELECT CASE WHEN @id = 1 THEN
到此
IF @id = 1 THEN
因为你不能像这样使用CASE
表达式,它应该在查询中使用。这样你的代码块应该看起来像
IF @id = 1 THEN
(select a.name, b.roles from employee a
INNER JOIN department b ON a.id = b.id
where b.years IN (@year)
OR b.roles IS NOT NULL )
ELSE
(select a.name, b.dayoff from employee a
INNER JOIN department b ON a.id = b.id
where b.years IN (@year)
OR b.dayoff IS NOT NULL )