创建函数返回整数SQL Server 2008

nlejzf6q  于 2022-10-22  发布在  SQL Server
关注(0)|答案(4)|浏览(191)

我试图创建一个返回整数的函数。然而,我得到的警告是

"Msg 2715, Level 16, State 3, Procedure median, Line 1 
Column, parameter, or variable #0: Cannot find data type Median."

这是查询。提前谢谢。

CREATE FUNCTION dbo.median (@score int)
RETURNS Median
AS
BEGIN
DECLARE @MedianScore as Median;
SELECT @MedianScore=
(
 (SELECT MAX(@score) FROM
   (SELECT TOP 50 PERCENT Score FROM t ORDER BY Score) AS BottomHalf)
 +
 (SELECT MIN(@score) FROM
   (SELECT TOP 50 PERCENT Score FROM t ORDER BY Score DESC) AS TopHalf)
) / 2 ;
RETURN @MedianScore;
END;
GO
y3bcpkx1

y3bcpkx11#

只需将返回类型更改为integer:

CREATE FUNCTION dbo.median (@score int)
RETURNS integer
AS
BEGIN
DECLARE @MedianScore as integer;

除非您有意将Median类型用于您尚未说明的内容。

z8dt9xmd

z8dt9xmd2#

由于您正在计算某些值的中值,我建议您返回数值而不是整数,因为MAX(@score)+MIN(@score)/2可以返回十进制数值。因此尝试将该值保存在INT变量中会截断Decimal部分。这可能导致错误的结果。
在下面的示例中,我使用了NUMERIC(20,2)返回值。

CREATE FUNCTION dbo.median (@score int)
RETURNS NUMERIC(20,2)
AS
BEGIN
DECLARE @MedianScore as NUMERIC(20,2);
SELECT @MedianScore=
(
 (SELECT MAX(@score) FROM
   (SELECT TOP 50 PERCENT Score FROM t ORDER BY Score) AS BottomHalf)
 +
 (SELECT MIN(@score) FROM
   (SELECT TOP 50 PERCENT Score FROM t ORDER BY Score DESC) AS TopHalf)
) / 2 ;
RETURN @MedianScore;
END;
GO

或者如果您确实想在函数内部返回一个INTEGER use-round函数,如下图所示。。

CREATE FUNCTION dbo.median (@score int)
RETURNS INT
AS
BEGIN
DECLARE @MedianScore as INT;
SELECT @MedianScore=ROUND(
(
 (SELECT MAX(@score) FROM
   (SELECT TOP 50 PERCENT Score FROM t ORDER BY Score) AS BottomHalf)
 +
 (SELECT MIN(@score) FROM
   (SELECT TOP 50 PERCENT Score FROM t ORDER BY Score DESC) AS TopHalf)
) / 2, 0) ;
RETURN @MedianScore;
END;
GO
siv3szwd

siv3szwd3#

必须在RETURNS上声明数据类型。“Median”不是类型。

CREATE FUNCTION dbo.median (@score int)
RETURNS real   -- you can use also float(24), numeric(8,3), decimal(8,3)...
AS
BEGIN
DECLARE @MedianScore as real;
SELECT @MedianScore=
(
 (SELECT MAX(@score) FROM
   (SELECT TOP 50 PERCENT Score FROM t ORDER BY Score) AS BottomHalf)
 +
 (SELECT MIN(@score) FROM
   (SELECT TOP 50 PERCENT Score FROM t ORDER BY Score DESC) AS TopHalf)
) / 2 ;
RETURN @MedianScore;
END;
GO
yzuktlbb

yzuktlbb4#

create function [dbo].[Sum]
    ( 
      @x int,
      @y int
    )   
    RETURNS int
    AS
    BEGIN
       return @x+@y
    END

相关问题