Sql server 关键字';如果';
为什么在下面的SQL中出现“关键字'IF'附近的语法不正确”Sql server 关键字';如果';,sql-server,sql-server-2008,Sql Server,Sql Server 2008,为什么在下面的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.Em
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
内联表值函数中不能有任何控制语句流。如果
@dpt为空
,查询仍将返回一个空结果集
编辑:如果数据类型正确,至少会编辑。您有@DPT INT
,正在与名称
列进行比较。这似乎注定要在执行时失败
编辑2:
作为一种解决方案,您可以1)如果@DPT不为null,只需删除,2)也可以
- 将
@DPT
参数的类型从INT
更改为类似于varchar(100)
,如果函数应该按名称搜索部门
或
- 将
WHERE
子句更改为如下内容:
where d.departmentid = @dpt
如果你想按部门ID搜索
试试这个
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
哦,没什么,真的。我想,如果我单独发布,我的答案看起来会不完整,除非我选择用“就像马丁指出的那样……”这样枯燥的评论重复你的观点。