Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subtract variables in SQL

How can I subtract values in two variables. Here is what I have done so far

DECLARE @A NVARCHAR(MAX)
DECLARE @B NVARCHAR(MAX)

SET @A='select count(abc)
 from x'
 EXEC (@A)
 PRINT @A

 SET @B= ' select count(xyz)
 from  y'

 EXEC (@B)
 PRINT @B

 DECLARE @C INT
 SET @C = CAST(@A AS INT) - CAST(@B AS INT)
 EXEC (@C)
 PRINT @C

I am getting conversion error

Msg 245, Level 16, State 1, Line 20
Conversion failed when converting the nvarchar value

like image 572
Kochikaaran Avatar asked Mar 17 '26 15:03

Kochikaaran


1 Answers

Of course you get a conversion error, because the variable is a string. Even if the string is a query, if you execute it you are not storing the result back to your variable. What you need to do is something along the lines of:

DECLARE @A INT, @B INT, @C INT;

SELECT @A = COUNT(abc)
FROM x;

SELECT @B = COUNT(xyz)
FROM y;

SET @C = @A - @B;
like image 146
Lamak Avatar answered Mar 19 '26 05:03

Lamak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!