如何减去两个变量中的值。这是我到目前为止所做的事情
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
我收到转换错误
Msg 245,Level 16,State 1,Line 20
转换nvarchar值时转换失败
答案 0 :(得分:7)
当然,您会收到转换错误,因为该变量是一个字符串。即使字符串是查询,如果执行它,也不会将结果存储回变量。你需要做的是:
DECLARE @A INT, @B INT, @C INT;
SELECT @A = COUNT(abc)
FROM x;
SELECT @B = COUNT(xyz)
FROM y;
SET @C = @A - @B;
答案 1 :(得分:2)
在您的代码中,@A
和@B
将保存sql语句,而不是结果。如果你想运行一个dunamic sql语句并从中获取一些输出,你需要检查sp_executesql你可以在哪里定义输出参数。
您的代码的正确实现如下:
DECLARE @A NVARCHAR(MAX)
DECLARE @B NVARCHAR(MAX)
DECLARE @SQLString nvarchar(500);
DECLARE @ParmDefinition nvarchar(500);
SET @SQLString = N'select @test = count(abc) from x'
SET @ParmDefinition = N'@test int OUTPUT';
EXECUTE sp_executesql @SQLString, @ParmDefinition, @A=@test OUTPUT;
SET @SQLString = N'select @test = count(xyz) from y'
EXECUTE sp_executesql @SQLString, @ParmDefinition, @B=@test OUTPUT;
DECLARE @C INT
SET @C = CAST(@A AS INT) - CAST(@B AS INT)
PRINT @C
另一个注意事项是,将@A
和@B
声明为(MAX)
太多了......
如果你将它们声明为INT
并避免额外的演员表会更好:
DECLARE @A INT
DECLARE @B INT
DECLARE @SQLString nvarchar(500);
DECLARE @ParmDefinition nvarchar(500);
SET @SQLString = N'select @test = count(abc) from x'
SET @ParmDefinition = N'@test int OUTPUT';
EXECUTE sp_executesql @SQLString, @ParmDefinition, @A=@test OUTPUT;
SET @SQLString = N'select @test = count(xyz) from y'
EXECUTE sp_executesql @SQLString, @ParmDefinition, @B=@test OUTPUT;
DECLARE @C INT
SET @C = @A - @B
答案 2 :(得分:0)
测试数据:
IF OBJECT_ID(N'Table1')>0
BEGIN
DROP TABLE Table1
END
IF OBJECT_ID(N'Table2')>0
BEGIN
DROP TABLE Table2
END
CREATE TABLE Table1 (Col1 VARCHAR(100))
CREATE TABLE Table2 (Col2 VARCHAR(100))
INSERT INTO Table1
VALUES('1'),('2'),('3'),('4')
INSERT INTO Table2
VALUES('2'),('4')
查询:
DECLARE @A NVARCHAR(MAX)
DECLARE @B NVARCHAR(MAX)
DECLARE @C INT
DECLARE @ACount INT
DECLARE @BCount INT
SET @A='SELECT @ACount = COUNT(Col1) FROM Table1'
SET @B='SELECT @BCount = COUNT(Col2) FROM Table2'
exec sp_executesql @A, N'@ACount int out', @ACount out
exec sp_executesql @b, N'@BCount int out', @BCount out
SET @C = @ACount - @BCount
PRINT @C
<强>清理:强>
IF OBJECT_ID(N'Table1')>0
BEGIN
DROP TABLE Table1
END
IF OBJECT_ID(N'Table2')>0
BEGIN
DROP TABLE Table2
END