如果日期差异已经大于或等于30,我编写了一个返回1的函数。
这是我的代码:
DECLARE @flag int
DECLARE @isactive bit
DECLARE @date Datetime
SET @flag = 0
SELECT @isactive = [m_isactive]
FROM dbo.rms_month_email
WHERE m_id = 3
SELECT @date = [m_createddate]
FROM dbo.rms_month_email
WHERE m_id = 3
IF (@isactive = 1 AND DATEDIFF(dd,@date,GETDATE()) = 30)
SET @flag = 1
RETURN @flag
但它产生了这个错误:
Msg 178,Level 15,State 1,Line 16
带有返回值的RETURN语句不能在此上下文中使用。
这是什么意思?
CREATE FUNCTION [dbo].[udf_isBonus]
(@m_id AS INT)
RETURNS INT
AS
BEGIN
-- Declare the return variable here
DECLARE @flag AS int
DECLARE @isactive AS bit
DECLARE @date AS Datetime
SET @flag = 0
SELECT @isactive = [m_isactive] FROM dbo.rms_month_email WHERE m_id = @m_id
SELECT @date = [m_createddate] FROM dbo.rms_month_email WHERE m_id = @m_id
IF (@isactive = 1 AND DATEDIFF(dd,@date,GETDATE()) = 30)
SET @flag = 1
RETURN @flag
END
GO
这是此功能的完整代码。
答案 0 :(得分:6)
您需要了解Return
仅适用于函数或存储过程。如果您没有在函数或存储过程中使用它,那么它只是一批select语句。因此,您需要使用select
代替return
。
<强> SQL DEMO 强>
修改强>
将其修改为函数后的编辑工作完全正常。
<强> SQL DEMO 强>
答案 1 :(得分:2)
尝试使用CASE
代替IF
并删除SET @flag = 0
:
USE [petc_rms]
GO
/****** Object: UserDefinedFunction [dbo].[udf_isBonus] Script Date: 9/29/2015 3:35:49 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[udf_isBonus]
(
-- Add the parameters for the function here
@m_id AS INT
)
RETURNS INT
AS
BEGIN
-- Declare the return variable here
DECLARE @flag AS int
DECLARE @isactive AS bit
DECLARE @date AS Datetime
SELECT @isactive = [m_isactive] FROM dbo.rms_month_email WHERE m_id = @m_id
SELECT @date = [m_createddate] FROM dbo.rms_month_email WHERE m_id = @m_id
SET @flag = CASE WHEN @isactive = 1 AND DATEDIFF(dd,@date,GETDATE()) = 30 THEN 1 ELSE 0 END
Return @flag
END
GO
查看如何CREATE FUNCTION