我陷入了一个简单的SQL Server标量值函数返回0的情况。 谁能告诉我我做错了什么。
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER FUNCTION [dbo].[OpeningBalance]
(
@AccountCode AS varchar,
@FromDate AS datetime
)
RETURNS numeric
AS
BEGIN
DECLARE @Balance AS numeric
SELECT
@Balance = SUM(Debit) - SUM(Credit)
FROM
(
SELECT
CASE
WHEN Debit - Credit > 0 THEN Debit - Credit
ELSE 0
END AS Debit,
CASE
WHEN Credit - Debit > 0 THEN Credit - Debit
ELSE 0
END AS Credit
FROM
(
SELECT
SUM(VoucherDetail.Debit) AS Debit,
SUM(VoucherDetail.Credit) AS Credit
FROM VoucherMaster AS VoucherMaster
INNER JOIN VoucherDetail AS VoucherDetail
ON VoucherMaster.ID = VoucherDetail.VoucherMasterID
WHERE (VoucherDetail.AccountCode = @AccountCode)
AND (VoucherMaster.VoucherDate < @FromDate)
) AS Data
UNION ALL
SELECT
CASE
WHEN OpeningBalance > 0 THEN OpeningBalance
ELSE 0
END AS Debit,
CASE
WHEN OpeningBalance < 0 THEN OpeningBalance * - 1
ELSE 0
END AS Credit
FROM ChartofAccounts
WHERE (AccountCode = @AccountCode)
) AS OpeningData
RETURN @Balance
END
但是,如果我在查询分析器中运行此查询,它会给我所需的答案。