Forum Discussion
SmithToronto
Jun 21, 2024Copper Contributor
Help in varchar column calculation
Hi, How I can calculate and get the calculation result of calc4 colum. Currently this is varchar but i want to calculate calc1+calc2+calc3 in calc4. Create table Calculation (Calc1 numeric (10,2)...
olafhelper
Jun 21, 2024Bronze Contributor
SmithToronto , normally I would let the backend/frontend, in plain SQL it's to error-prone; but this should work:
Create table ##Calculation (Calc1 numeric (10,2), calc2 numeric (10,2), Calc3 numeric (10,2), Calc4 varchar(40))
insert into ##Calculation
values (6,7,8, 'calc1+calc2+calc3');
DECLARE @sql nvarchar(4000);
SET @sql = (SELECT N'SELECT C.Calc1, C.Calc2, C.Calc3, ' + C.Calc4 + N' ' +
N'FROM ##Calculation AS C'
FROM ##Calculation AS C);
EXEC sp_executesql @sql
GO
DROP TABLE ##Calculation;
GO
- SmithTorontoJun 22, 2024Copper ContributorHi,
Desired result :
Select * from Calculation
Calc1 calc2 Calc3 Calc4
6 7 8 22
9 9 9 27- olafhelperJun 24, 2024Bronze Contributor
SmithToronto , as I wrote, error-prone.
You can use a cursor to loop through all records.
- SmithTorontoJun 24, 2024Copper ContributorHi olafhelper, Can you please help on this SQL? Thanks
- SmithTorontoJun 21, 2024Copper Contributor
olafhelper When i add one more row and then execute the query then got the error that 'Subquery returned more than 1 value..'
- SmithTorontoJun 21, 2024Copper ContributorI am not able to execuete the query after adding following one more row
insert into ##calculation
values (9,9,9,'calc1+calc2+calc3')
Error after executing the query: Subquery returned more than 1 values