T-SQL:COUNT不正确

时间:2011-03-08 05:01:25

标签: sql sql-server-2008 aggregate-functions

我需要在SQL Server 2008中的SQL函数内执行以下查询。

注意:@ ncuota,@ ccod,@ cfcha和@rut是函数的参数,设置为正确的变量类型。

DECLARE @cpagos int
SELECT @cpagos = COUNT(Pago_NPago)
FROM Pago_Costa AS p INNER JOIN
(
SELECT Cancela_NPago, Cancela_TipoPago
FROM Cancela_Costa AS cc INNER JOIN Cuota_Costa AS cuota
ON Cancela_ConcCod = Cuota_ConcCod AND Cancela_ConcFecha = Cuota_ConcFecha
WHERE Cuota_NCuota = @ncuota AND Cancela_ConcCod = @ccod AND Cancela_ConcFecha = @cfecha
) AS c
ON c.Cancela_NPago=p.Pago_NPago AND c.Cancela_TipoPago = p.Pago_TipoPago
WHERE Pago_AlumnoRut = @rut
GROUP BY Pago_AlumnoRut

但是,@ ipagos获取NULL值(如果我使用GROUP BY)或0(如果我没有),但如果我执行查询作为常规查询而不是在函数内部,它可以正常工作并返回价值2.这里有什么问题?提前谢谢。

表定义:

Pago_Costa:
- Pago_NPago PK bigint
- Pago_TipoPago PK bit
- Pago_AlumnoRut FK nvarchar(9)
- Pago_Monto bigint
- Pago_FPago date
- Pago_TipoDoc smallint
- Pago_RefBoleta FK bigint
- Pago_RefTipoPago FK bit
- Pago_Obs nvarchar(200)

Cuota_Costa
- Cuota_NCuota PK smallint
- Cuota_ConcCod FK PK smallint
- Cuota_ConcFecha PK FK int
- Cuota_Valor biging

Cancela_Costa
- Cancela_NPago PK FK bigint
- Cancela_TipoPago PK FK bit
- Cancela_NCuota PK FK smallint
- Cancela_ConcCod PK FK smallint
- Cancela_ConcFecha PK FK int
- Cancela_Monto bigint
- Cancela_Cheque FK nvarchar(20)

FUNCTION。我将使用我用来测试查询的函数的修改版本。

FUNCTION verificaPagoCuotas
(
@rut nvarchar,
@ncuota smallint,
@ccod smallint,
@cfecha int
)
RETURNS int
AS
BEGIN
DECLARE @cpagos int, @valor bigint
-- @valor is the real variable to be returned, but right now we're testing so it'll be @cpagos
SET @cpagos = (SELECT COUNT(Pago_NPago)
FROM Pago_Costa AS p INNER JOIN
(
SELECT Cancela_NPago, Cancela_TipoPago
FROM Cancela_Costa AS cc INNER JOIN Cuota_Costa AS cuota
ON Cancela_ConcCod = Cuota_ConcCod AND Cancela_ConcFecha = Cuota_ConcFecha AND Cancela_NCuota = Cuota_NCuota
WHERE Cancela_NCuota = @ncuota AND Cancela_ConcCod = @ccod AND Cancela_ConcFecha = @cfecha
) AS c
ON c.Cancela_NPago=p.Pago_NPago AND c.Cancela_TipoPago = p.Pago_TipoPago
WHERE Pago_AlumnoRut = @rut
RETURN @cpagos
... -- More irrelevant code
END

2 个答案:

答案 0 :(得分:1)

您需要缩小问题范围。首先,您应该使用Set而不是Select。如果返回多行,Set将抛出错误,而选择则不会。这就是为什么包含Group By在添加它时不会抛出错误,即使它应该。我会排除Group By。

现在,迭代尝试:

  1. 使用Count(*)代替Count(Pago_Npago)时的计数是多少?
  2. 仅使用内部联接时的计数是多少?
  3. 排除Where Pago_Alumnorut = @Rut
  4. 时的计数是多少
  5. 将内部联接更改为左联接并将计数更改为Count(Cancela_NPago)时的计数是多少?
  6.   
        

    当你消除不可能的事物时,无论多么不可能,遗体都必须是真理。

      

    如果直接在SSMS中运行查询并使用相同参数的函数,并且结果不同,则函数中的查询必须与您在SSMS中运行的查询不同。

答案 1 :(得分:0)

答案太简单了。我的问题是我只声明了“nvarchar”,但我没有指定长度。当我更改为nvarchar(8)时,问题自动修复。感谢您的大力帮助!