我想查看过去一年内是否有日期,如果是,则将值增加1.所以我尝试了以下操作,但它返回以下错误:
Msg 102,Level 15,State 1,Procedure IsComplete,Line 41 [Batch Start Line 7]
'@compliant'附近的语法不正确。
代码:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[IsComplete] (@input VARCHAR(9))
RETURNS CHAR(1)
AS
BEGIN
DECLARE @idnum VARCHAR(9)
DECLARE @complete CHAR
DECLARE @cert int
DECLARE @compliant int
SET @idnum = SUBSTRING(@input, 0, 9)
SET @compliant = 0
SET @cert = (SELECT DATEDIFF(month, CertifiedDate, GETDATE())
FROM Profile
WHERE IDNumber = @idnum)
BEGIN
IF @cert > 11
BEGIN
@compliant = @compliant + 1
END
ELSE
BEGIN
-- do nothing
END
END
RETURN @complete
END
看起来很简单,但我无法让它工作,因为它会产生错误并且无法编译。有人能指出我正确的方向吗?
答案 0 :(得分:3)
SET @compliant = @compliant +
(SELECT
case when DATEDIFF(month, CertifiedDate, GETDATE()) > 11 then 1 else 0 end
FROM Profile
WHERE IDNumber = @idnum)
答案 1 :(得分:1)
根据错误,在函数的第25行,您只是忘记添加SET
。所以改变如下:
SET @compliant = @compliant + 1
答案 2 :(得分:0)
这是因为你的Else
子句是空的,而且SQL不喜欢空子句。
删除整个' Else'部分(因为它什么也不做),你的查询应该编译:)
答案 3 :(得分:0)
请尝试以下查询:
USE [CDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[IsComplete] (@input VARCHAR(9))
RETURNS CHAR(1)
AS BEGIN
DECLARE @idnum VARCHAR(9)
DECLARE @complete CHAR
DECLARE @cert int
DECLARE @compliant int
SET @idnum = SUBSTRING(@input, 0, 9)
SET @compliant = 0
SET @cert = (SELECT DATEDIFF(month, CertifiedDate, GETDATE()) FROM Profile WHERE IDNumber = @idnum)
BEGIN
IF @cert > 11
BEGIN
SET @compliant = @compliant + 1
END
--ELSE
-- BEGIN
-- -- do nothing
-- END
END
RETURN @complete
END
说明:
我的查询只做了两处小改动:
SET
添加到第@compliant = @compliant + 1
行ELSE
阻止。 如果您愿意,您显然可以稍后简化您的逻辑。但是,最好先修复错误。
看看它是否有效。