Link to home
Start Free TrialLog in
Avatar of Sevron
Sevron

asked on

MS SQL Error converting datatype varchar to numeric

Hi,

Below I have a stored procedure that I am currently working on, When I run this stored procedure i get the following error:

Msg 8114, Level 16, State 5, Procedure SP_plottotals, Line 26
Error converting data type varchar to numeric.

Open in new window


What am I doing wrong? The plot#_total column in the database is set to decimal(18,2) as the data type.

I am trying to select the SUM of a column from a table into a variable in the first statement and then updating another column with the value of the SUM variable in the second statement.

The Procedure is:

/*
  [SP_plottotals] 243, 1
*/
ALTER PROCEDURE [dbo].[SP_plottotals]
	-- Add the parameters for the stored procedure here
     @PKCPID int
    ,@plot int
    
AS

DECLARE @i int
DECLARE @sql nvarchar(500)
DECLARE @plottotal decimal(18,2)


set @i = 1
WHILE (@i <= (400))
BEGIN


set @sql = '
SELECT '+@plottotal+' = SUM(plot'+cast(@plot as varchar(100))+'_total) FROM tblprojects_plantlist WHERE FKCPID='+cast(@PKCPID as varchar(100))+''

print @sql

exec sp_executesql @sql

END

DECLARE @i2 int
DECLARE @sql2 nvarchar(500)


set @i2 = 1
WHILE (@i2 <= (400))
BEGIN


set @sql2 = '
 UPDATE
	tblplotinvoicing
SET
	plot'+cast(@plot as varchar(100))+'_total = '+cast(@plottotal as varchar(200))+'
WHERE FKCPID='+cast(@PKCPID as varchar(100))+''

print @sql2

exec sp_executesql @sql2

END

Open in new window


Thanks.
SOLUTION
Avatar of Jim Horn
Jim Horn
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Sevron
Sevron

ASKER

Thank you for your help. I've implemented both of your answers which helped and managed to fix the new problem myself. Thanks again.