Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 关键字';如果';_Sql Server_Sql Server 2008 - Fatal编程技术网

Sql server 关键字';如果';

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

为什么在下面的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

内联表值函数中不能有任何控制语句流。如果
@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

哦,没什么,真的。我想,如果我单独发布,我的答案看起来会不完整,除非我选择用“就像马丁指出的那样……”这样枯燥的评论重复你的观点。