I've written an SQL statement to update a database as follows:
UPDATE Agent SET previousBalanceDue = (select isnull(dbo.fnGetAgentTotalBalanceDue(taxIdNumber),0))
The statement fails with the follwing message:
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
If I run only the innner select query using a string literal the function returns a single value, i.e.:
select isnull(dbo.fnGetAgentTotalBalanceDue('000000002'),0)
How can my UPDATE statement be modified to so that the scalar-valued function returns only one row for each row that the UPDATE statement is updating?
Here is the code for the scalar-valued function:
ALTER FUNCTION [dbo].[fnGetAgentTotalBalanceDue]
(
-- Add the parameters for the function here
@TaxIdNumber char(9)
)
RETURNS money
AS
BEGIN
-- Declare the return variable here
DECLARE @Result money
-- Add the T-SQL statements to compute the return value here
SELECT @Result =
(SELECT a.previousBalanceDue +
SUM(i.newAmount) +
SUM(i.renewalAmount) -
SUM(i.refundAmount) -
SUM(i.newAmountRetained) -
SUM(i.renewalAmountRetained) -
SUM(i.refundAmountRetained) as AgentTotalBalanceDue
FROM Agent a JOIN Ismdata i ON a.taxIdNumber = i.taxIdNo WHERE a.taxIdNumber = @TaxIdNumber GROUP BY a.previousBalanceDue)
-- Return the result of the function
RETURN @Result
END
UPDATE Agent SET previousBalanceDue = (select isnull(dbo.fnGetAgentTotalBalanceDue(taxIdNumber),0))
The statement fails with the follwing message:
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
If I run only the innner select query using a string literal the function returns a single value, i.e.:
select isnull(dbo.fnGetAgentTotalBalanceDue('000000002'),0)
How can my UPDATE statement be modified to so that the scalar-valued function returns only one row for each row that the UPDATE statement is updating?
Here is the code for the scalar-valued function:
ALTER FUNCTION [dbo].[fnGetAgentTotalBalanceDue]
(
-- Add the parameters for the function here
@TaxIdNumber char(9)
)
RETURNS money
AS
BEGIN
-- Declare the return variable here
DECLARE @Result money
-- Add the T-SQL statements to compute the return value here
SELECT @Result =
(SELECT a.previousBalanceDue +
SUM(i.newAmount) +
SUM(i.renewalAmount) -
SUM(i.refundAmount) -
SUM(i.newAmountRetained) -
SUM(i.renewalAmountRetained) -
SUM(i.refundAmountRetained) as AgentTotalBalanceDue
FROM Agent a JOIN Ismdata i ON a.taxIdNumber = i.taxIdNo WHERE a.taxIdNumber = @TaxIdNumber GROUP BY a.previousBalanceDue)
-- Return the result of the function
RETURN @Result
END