为什么我在以下SQL中得到“关键字'IF'附近的语法不正确?”:
use AdventureWorks
CREATE FUNCTION Query2_Function(@DPT INT)
RETURNS TABLE
AS
RETURN
IF @DPT is not null
select edh.departmentid,d.name,count(*)as cnt
From HumanResources.Employee e
inner join HumanResources.EmployeeDepartmentHistory edh on e.employeeID = edh.employeeid
inner join humanresources.department d on edh.departmentid = d.departmentid
where d.Name = @dpt
group by edh.departmentid, d.name
答案 0 :(得分:4)
在内联表值函数中不能有任何控制语句流。如果@dpt is null
查询将返回空结果集
编辑:或者至少是否是正确的数据类型。您有@DPT INT
并且正在与name
列进行比较。这似乎注定要在执行时失败。
编辑2:
作为解决方案,您可以1)简单地删除IF @DPT is not null
行和2)
@DPT
参数的类型从INT
更改为varchar(100)
,如果该函数应该按名称搜索部门,或
将WHERE
子句更改为以下内容:
where d.departmentid = @dpt
如果您打算按部门ID搜索。
答案 1 :(得分:2)
试试这个
CREATE FUNCTION Query2_Function(@DPT INT)
RETURNS @tbl TABLE
(
departmentid int ,
[name] varchar(100),
cnt int
)
AS
begin
IF @DPT is not null
insert into @tbl (departmentid,name,cnt)
select edh.departmentid,d.name,count(*)as cnt
From HumanResources.Employee e
inner join HumanResources.EmployeeDepartmentHistory edh on e.employeeID = edh.employeeid
inner join humanresources.department d on edh.departmentid = d.departmentid
where d.DepartmentID =@DPT
group by edh.departmentid, d.name
return
end
GO