Ibibo
Ibibo

Reputation: 197

Calculate the value of column in stored procedure

I have a stored procedure.

I want to add the value of column1 with column2 to like:

column3 = (@column1 + @column2)

Instead of adding the values my sql stored procedure is concatenating the value.

I declared

column1 = 20
column2 = 40

The answer must be column3 = 60 but I am getting column3 = 2040.

But in the main table, column1 and column2 are declared as nvarchar and I cannot change the table. I tried to convert the column in the stored procedure but getting same anser I converted as convert(float,@column1) and convert(float,@column2)

Upvotes: 0

Views: 1372

Answers (4)

gofr1
gofr1

Reputation: 15987

DECLARE @test TABLE (
    column1 nvarchar(50),
    column2 nvarchar(50)
)

INSERT INTO @test VALUES
(20, 40),
('20','40')

SELECT CAST(column1 as int) + CAST(column2 as int) as column3
FROM @test

SELECT CAST(column1 as float) + CAST(column2 as float) as column3
FROM @test

Will give you:

column3
60
60

Upvotes: 1

Asad Ali
Asad Ali

Reputation: 361

Define datatypes of parameters properly.

You should do something like this:

Declare @column1 INT = 20, @column2 INT = 40, @column3 INT

SET @column3 = @column1 + @column2;

SELECT @column3 AS [Result];

Tested on my end. Hope That Helps... :)

Upvotes: 1

Amit Yadav
Amit Yadav

Reputation: 481

You should use Cast function:

select Cast(column_1 as float)+cast(Column_2 as Float) Column_3

Upvotes: 3

Rajesh Ranjan
Rajesh Ranjan

Reputation: 537

Datatype of the columns may be string.

You should try..

        column3 = (cast(@column1 as int) + cast(@column2 as int))

Upvotes: 3

Related Questions