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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With