我的存储过程包含CASE
语句。但是,我需要根据参数定义列而不是值的参数来选择它。
这可能吗?
以下是我尝试的内容:
CREATE PROCEDURE HR.GetRequestByPriv
@colKey VARCHAR(50)
AS
DECLARE @empName VARCHAR(100)
SELECT
@empName = (HR.EmployeeRec.fname + ' ' + HR.EmployeeRec.lname)
FROM
HR.LeaveRec
INNER JOIN
HR.EmployeeRec ON HR.LeaveRec.EmployeeRecNo = HR.EmployeeRec.recno
WHERE
CASE
WHEN @colKey = 'isApprove' THEN HR.LeaveRec.isApprove
WHEN @colKey = 'isNote' THEN HR.LeaveRec.isNote
WHEN @colKey = 'isVerify' THEN HR.LeaveRec.isVerify
END = 0
RETURN @empName
希望得到你的帮助。谢谢。
答案 0 :(得分:1)
您选择必须为零的列的代码部分看起来很好。
但是a stored procedure return value总是一个整数。所以这不会起作用:
create procedure dbo.YourSP
as
declare @var varchar(50)
select @var = 'Oops this won''t work'
return @var -- Since @var is not an integer, this won't work as expected
通常的方法是返回一个rowset。任何未分配变量的select
都会返回行集。例如:
create procedure dbo.YourSP
as
select 'Returning a rowset'
另一个选项是输出参数:
create procedure dbo.YourSP
@var varchar(50) output
as
select @var = 'Returning an output parameter'
答案 1 :(得分:1)
我很困惑。你说你想要一个存储过程但是你要返回一些东西。 Andomar有一个解决方案,它是一个输出参数。我怀疑你真的想要一个功能。在这种情况下,您可以创建一个单语句,表值函数,这很像一个带参数的视图:
CREATE FUNCTION HR.GetRequestByPriv (
@colKey VARCHAR(50)
)
RETURNS TABLE as
RETURN(SELECT (l.fname + ' ' + l.lname) as EmpName
FROM HR.LeaveRec l NNER JOIN
HR.EmployeeRec e
ON l.EmployeeRecNo = e.recno
WHERE (@colKey = 'isApprove' AND HR.LeaveRec.isApprove = 0) OR
(@colKey = 'isNote' AND HR.LeaveRec.isNote = 0) OR
(@colKey = 'isVerify' AND HR.LeaveRec.isVerify)
);
然后,您可以在select
语句中将其称为:
select *
from HR.GetRequestByPriv('isNote');
答案 2 :(得分:0)
这种小程序的最简单方法是使用IF
。在3个IF
/ ELSE
块中使用3个不同的SELECT语句,就是这样。像这样:
IF @colKey = 'isApprove'
SELECT @empName = (HR.EmployeeRec.fname + ' ' + HR.EmployeeRec.lname)
FROM HR.LeaveRec INNER JOIN HR.EmployeeRec ON HR.LeaveRec.EmployeeRecNo = HR.EmployeeRec.recno
WHERE HR.LeaveRec.isApprove = 0
ELSE
BEGIN
IF @colKey = 'isNote'
SELECT @empName = (HR.EmployeeRec.fname + ' ' + HR.EmployeeRec.lname)
FROM HR.LeaveRec INNER JOIN HR.EmployeeRec ON HR.LeaveRec.EmployeeRecNo = HR.EmployeeRec.recno
WHERE HR.LeaveRec.isNote = 0
ELSE
...
END