检查返回表SQL Server 2008的函数中的输入参数

时间:2016-04-21 17:15:13

标签: sql sql-server sql-server-2008

我在检查此问题时遇到了问题。

到目前为止,我已经能够返回表格,但不会对函数进行检查。如果函数返回一个整数或在一个过程中创建一个整数,我可以这样做。到目前为止,这是我的代码:

alter function NumofEmply(@department char(25))
returns table 
as
   return
       (select count(*) #ofEmp, pc.empnum
        from employee inner join pc on employee.empnum = pc.empnum
        where location = @department 
        group by pc.empnum
        having count(*) in 
(select count(*)
from employee 
inner join pc on employee.empnum = pc.empnum
group by location
having count(*) <= 1)
)

select *
from dbo.NumofEmply('info sys')

如何添加检查函数输入是否有效的方法? '检查部门'

1 个答案:

答案 0 :(得分:0)

更新的答案 - 感谢Sean指出RETURN中不允许使用条件。

ALTER FUNCTION NumofEmply(@Department CHAR(25))
RETURNS @EmployeePCs TABLE
(
    EmpNum INT,
    PcCount INT,
    StatusMessage   VARCHAR(100)
)
AS
BEGIN

    IF (EXISTS(SELECT * FROM Employee WHERE Location = @Department))
    BEGIN
       INSERT INTO @EmployeePCs
       SELECT 
       PC.EmpNum,
       COUNT(PC.EmpNum) AS PCCount,
      'Department was found.' AS StatusMessage
       FROM Employee E
           INNER JOIN PC ON E.EmpNum = P.EmpNum
       WHERE Location = @Department
       GROUP BY pc.empnum
       HAVING COUNT(PC.EmpNum) < 2

    END
    ELSE
    BEGIN
       INSERT INTO @EmployeePCs
       SELECT 
       0 AS EmpNum,
       0 AS PCCount,
      'No employees in that department!' AS StatusMessage
    END

    RETURN 
END