这是我的查询:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[GetTotalComp]
(@bonus DECIMAL, @empsalary MONEY)
RETURNS INT
AS
-- Returns total compensation
BEGIN
DECLARE @totalComp money
IF @bonus is NULL
set @totalComp=@empsalary
else If (@empsalary>50000) and (@empsalary<=100000)
set @totalComp=@empsalary+(@bonus*@empsalary)
else if (@empsalary>100000)
set @totalComp=@empsalary + 2*(@bonus*@empsalary)
RETURN @totalComp;
END;
declare @param varchar(25)
set @param=392
IF @param=0
select LName,Fname, Isnull(Name,'Unassinged') as DeptName,'$' + convert(varchar,dbo.GetTotalComp(d.bonus,e.salary),-1) as TotalComp from Emp e
left join EmpInDept ed on e.empid=ed.empid
left join Dept d on ed.deptid=d.deptid
ELSE
select LName,Fname, Isnull(Name,'Unassinged') as DeptName,'$' + convert(varchar,dbo.GetTotalComp(d.bonus,e.salary),-1) as TotalComp from Emp e
left join EmpInDept ed on e.empid=ed.empid
left join Dept d on ed.deptid=d.deptid
where d.deptid=@param
我收到此错误消息:
消息156,级别15,状态1,过程GetTotalComp,第19行[批处理开始第4行] 关键字'THEN'附近的语法不正确。
通常,查询不应该像脚本一样创建函数。
但是,如果您确实需要在一个脚本中使用它,则需要在查询和创建函数脚本之间添加关键字GO
。
此外,由于您的脚本正在创建一个函数,这意味着它只会运行一次,因为它会说第二次该函数已经存在。所以我为此添加了额外的代码。
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF OBJECT_ID('dbo.GetTotalComp') IS NOT NULL
DROP FUNCTION dbo.GetTotalComp
GO
CREATE FUNCTION [dbo].[GetTotalComp]
(@bonus DECIMAL, @empsalary MONEY)
RETURNS INT
AS
-- Returns total compensation
BEGIN
DECLARE @totalComp money
IF @bonus is NULL
set @totalComp=@empsalary
else If (@empsalary>50000) and (@empsalary<=100000)
set @totalComp=@empsalary+(@bonus*@empsalary)
else if (@empsalary>100000)
set @totalComp=@empsalary + 2*(@bonus*@empsalary)
RETURN @totalComp;
END;
GO --THE KEYWORD YOU WERE MISSING HERE
declare @param varchar(25)
set @param=392
IF @param=0
select LName,Fname, Isnull(Name,'Unassinged') as DeptName,'$' + convert(varchar,dbo.GetTotalComp(d.bonus,e.salary),-1) as TotalComp from Emp e
left join EmpInDept ed on e.empid=ed.empid
left join Dept d on ed.deptid=d.deptid
ELSE
select LName,Fname, Isnull(Name,'Unassinged') as DeptName,'$' + convert(varchar,dbo.GetTotalComp(d.bonus,e.salary),-1) as TotalComp from Emp e
left join EmpInDept ed on e.empid=ed.empid
left join Dept d on ed.deptid=d.deptid
where d.deptid=@param
我会使这个内联表值函数而不是标量函数。它性能更高,更灵活。
create function GetTotalComp
(
@bonus decimal
, @empsalary money
) returns table as return
select TotalComp =
case when @bonus is null
then @empsalary
when @empsalary > 50000 and @empsalary <= 100000
then @empsalary + (@bonus * @empsalary)
when @empsalary > 100000
then @empsalary + 2 * (@bonus * @empsalary)
else
NULL
end
那么你的代码也可以大大简化。像这样的东西。
declare @param varchar(25)
set @param=392
select LName
, Fname
, Isnull(Name,'Unassinged') as DeptName
,'$' + convert(varchar(10), c.TotalComp , -1) as TotalComp
from Emp e
left join EmpInDept ed on e.empid = ed.empid
left join Dept d on ed.deptid = d.deptid
cross apply dbo.GetTotalComp(d.bonus, e.salary) c
where d.deptid = d.deptid
OR @param = 0