UDF中的聚合值始终为零,影响局部变量

时间:2014-07-28 19:56:12

标签: sql sql-server aggregate-functions user-defined-functions

以下UDF根据查询后执行的不同条件返回一个整数。变量@recCount始终为零,尽管它也可以大于零。它应包含使用COUNT(*)的内联查询的值。

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

ALTER FUNCTION [dbo].[fnGetConfID] (@eventID      INT,
                                    @conferenceID INT,
                                    @companyID    VARCHAR(32))
RETURNS INT
AS
  BEGIN
      -- Declare the return variable here
      DECLARE @confID INT; -- Conference ID we're passing back

      DECLARE @curAtt INT; -- Current attendance
      DECLARE @maxAtt INT; -- Max attendance
      DECLARE @waitConfID INT; --Waitlist value of current conference
      DECLARE @recCount INT; -- Total number of employees who selected same conference

      SELECT @confID = ec.conferenceID,
             @recCount = (SELECT count(*)
                          FROM   tblRegistration r
                                 INNER JOIN tblRegConferences rc
                                   ON r.ID = rc.regID
                          WHERE  r.optfield2 = @companyID
                                 AND r.eventID = @eventID
                                 AND rc.conferenceID = @conferenceID),
             @curAtt = ec.currentAttendance,
             @maxAtt = ec.maxAttendance,
             @waitConfID = ec.waitListProdID
      FROM   tblEventConferences ec
      WHERE  ec.conferenceID = @conferenceID
             AND ec.isWaitList = 0

      -- If no records were found (waitlist item)
      IF @@ROWCOUNT = 0
        BEGIN
            SET @confID = @conferenceID -- use same value we passed in
        END
      -- records found
      ELSE
        BEGIN
            --Max attendance not reached, return main conference ID
            IF @curAtt < @maxAtt
              BEGIN
                  SET @confID = @conferenceID
              END

            --Max attendance reached, return waitlist ID
            IF @curAtt >= @maxAtt
              BEGIN
                  SET @confID = @waitConfID
              END

            --Company cap reached, return waitlist ID
            IF @recCount > 1
              BEGIN
                  SET @confID = @waitConfID
              END
        END

      RETURN @confID
  END 

将其作为查询运行,我获得的字段companyCnt的值大于零,这是@recCount的等价物。

SELECT ec.conferenceID, (
        SELECT count(*)
        FROM tblRegistration r
            INNER JOIN tblRegConferences rc ON r.ID = rc.regID
        WHERE
            r.optfield2 = '83b90acc-42af-4de2-9279-76e80eb8b73a'
        AND
            r.eventID = 624
        AND
            rc.conferenceID = 8848
    ) AS companyCnt, ec.currentAttendance, ec.maxAttendance, ec.waitListProdID
    FROM
        tblEventConferences ec
    WHERE
        ec.conferenceID = 8848
    AND
        ec.isWaitList = 0

1 个答案:

答案 0 :(得分:0)

将@companyid从varchar(32)更改为varchar(50)。

您遇到此问题,因为查询中公司的长度为36个字符,因为变量仅声明为32个字符,SQL服务器不会发出警告,只会截断最后的字符。