[英]user defined function return statment in Scalar-Valued
I have a table with the following columns: 我有一个包含以下列的表格:
CREATE TABLE [dbo].[TblPerson](
[Id] [int] IDENTITY(1,1) NOT NULL,
[name] [nvarchar](30) NULL,
[Family] [nvarchar](40) NULL,
[address] [nvarchar](200) NULL,
[MeliCode] [char](10) NOT NULL,
[IsActive] [bit] NULL CONSTRAINT [DF_TblPerson_IsActive] DEFAULT ((0)),
[Count] [int] NULL CONSTRAINT [DF_TblPerson_Count] DEFAULT ((0)),
CONSTRAINT [PK_TblPerson] PRIMARY KEY CLUSTERED
(
Now i want to write a UDF which gets the Melicode as input parameter and if the IsActive = 1 then the UDF returns the value of count, else the UDF must return 0. i write the following function as 现在,我想编写一个将Melicode用作输入参数的UDF,如果IsActive = 1,则UDF返回count的值,否则UDF必须返回0。
CREATE FUNCTION ReturnMelli ( @Melicode CHAR(10) )
RETURNS INT
AS
BEGIN
DECLARE @RESULT BIT
SET @RESULT = ( SELECT Isactive
FROM TblPerson
WHERE MeliCode = @Melicode
)
DECLARE @R INT
SET @R = ( SELECT [Count]
FROM TblPerson
WHERE MeliCode = @Melicode
)
IF ( @RESULT = 1 )
BEGIN
RETURN @R
END
ELSE
BEGIN
RETURN 0
END
END
Then, there is problem with running the UDF as 然后,将UDF运行为
Msg 455, Level 16, State 2, Procedure ReturnMelli, Line 17
The last statement included within a function must be a return statement.
i don't get the reason of failure. 我不知道失败的原因。 Even i put the return value at the end, it doesn't work 即使我将返回值放在最后,它也不起作用
Replace this 取代这个
IF ( @RESULT = 1 )
BEGIN
RETURN @R
END
ELSE
BEGIN
RETURN 0
END
with this 有了这个
RETURN IIF(@RESULT = 1, @R, 0)
This link will Help you 此链接将为您提供帮助
Try like this .. 这样尝试..
CREATE FUNCTION ReturnMelli ( @Melicode CHAR(10) )
RETURNS INT
AS
BEGIN
DECLARE @RESULT BIT
SET @RESULT = ( SELECT Isactive
FROM TblPerson
WHERE MeliCode = @Melicode
)
DECLARE @R INT
SET @R = ( SELECT [Count]
FROM TblPerson
WHERE MeliCode = @Melicode
)
IF ( @RESULT <> 1 )
BEGIN
SET @R =0
END
RETURN @R
END
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.