简体   繁体   中英

Arithmetic overflow error converting varchar to data type numeric in the stored procedure (parameterised) caluculation

i want caluculate the grandtoal that includes vat,shippingcost,total,while caluculating the total by using @total getting the Arithmetic overflow error converting varchar to data type numeric error.how to resolve this

PROCEDURE   [dbo].[GrandTotal] 
@GrandTotal decimal(10,2)



as
BEGIN

DECLARE @1stQuery AS NVARCHAR(4000)
DECLARE @ParamDefinition AS NVARCHAR(2000)
DECLARE @Total AS decimal (18,12)
DECLARE @vat AS decimal (10,2)
DECLARE @Gtotal AS decimal (10,2)


    set @Total =  'select ((L.Quantity*L.Price)- L.DiscountValue-((O.AllocatedPoint / 100) * O.ExchangeRate))AS Total 
                    FROM [Orders] O 
                   LEFT JOIN [LineItem] L  ON O.[OrderId]  = L.[OrderId]  where L.[StatusCode] IN (''AS'', ''PP'',  ''P'',''PS'',''O'',''OH'',''SC'',''D'', ''GA'',''SW'')'


set @vat = @Total / (100 + 20) * 20;

set @Gtotal =@Total-@vat

set  @1stQuery =  
 ' select   orderid,GrandTotal from (SELECT  O.[OrderId],
     CAST( ROUND((@Gtotal+O.ShippingCost),2)AS DECIMAL(10,2)) AS GrandTotal
    FROM    LineItem L 
             left JOIN [Orders] O  ON O.[OrderId]  = L.[OrderId]
             left join [Country] C on O.[CountryId] = c.[CountryId]
               )as gt where 1=1 
         '


    if @GrandTotal  is not null 

    SET @1stQuery = @1stQuery + 'and  gt.[GrandTotal] = @GrandTotal   ' 


    set @ParamDefinition='@GrandTotal decimal (10,2),@Total decimal(18,12),@Gtotal decimal(10,2),@vat decimal(10,2)
                          '

   EXECUTE sp_Executesql @1stQuery,
                            @ParamDefinition,
                            @GrandTotal,
                            @Total,
                            @Gtotal,@vat


END

Your error is nothing to do with the calculation, it is because you have declared @total as decimal then assign it a string value. You can recreate the error using just:

DECLARE @Total AS decimal (18,12)

set @Total =  'select ((L.Quantity*L.Price)- L.DiscountValue-((O.AllocatedPoint / 100) * O.ExchangeRate))AS Total 
                FROM [Orders] O 
               LEFT JOIN [LineItem] L  ON O.[OrderId]  = L.[OrderId]  where L.[StatusCode] IN (''AS'', ''PP'',  ''P'',''PS'',''O'',''OH'',''SC'',''D'', ''GA'',''SW'')'

Which yields

Msg 8115, Level 16, State 6, Line 3

Arithmetic overflow error converting varchar to data type numeric.

For what it's worth, there are countless other errors with your query, or operations that I cannot see the logic behind, but it is not clear at all what you are trying to achieve, so I can't suggest an alternative yet. I will point out though that there is no need at all for dynamic SQL!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM