SQL根据库存和交易计算余额

我正在创建一个用于计算用户库存状态的存储过程。SQL根据库存和交易计算余额

设想以下的表称为user_inventory许多偶数列:

id_inventory id_user 0 1 2 3 

------------ ------- - - - -

2 4 5 0 14 21

而另一位叫user_transactions

id_tran id_user 0 1 2 3 

------- ------- - - - -

54 4 1 0 3 7

55 4 2 0 9 8

56 4 1 0 2 4

我想是计算每一列的剩余库存状态的方法减去所有用户交易的总和后,如下所示:

id_availableInventory id_user 0 1 2 3 

--------------------- ------- - - - -

2 4 1 0 0 2

附加障碍是,有从0标记的列499。

我试图使用while循环和使用动态SQL和SUM()在更新一次一列,但有两个范围和性能问题 - 我不确定这是否是解决此问题的好方法。我使用SQL Server 2012的

DECLARE @counter int 

DECLARE @userid int

DECLARE @amount int

DECLARE @sum int

declare @sql nvarchar(1000)

SET @counter = 0

SET @userid = 4

WHILE @counter < 500

BEGIN

set @sql = 'SELECT @amount = [' + CAST(@counter AS nvarchar) + '] FROM user_inventory WHERE ID_User = ' +CAST(@userid AS nvarchar)

EXEC(@sql)

set @sql = 'SELECT @sum = SUM([' + CAST(@counter AS nvarchar) + ']) FROM user_transactions WHERE ID_User = ' +CAST(@userid AS nvarchar)

EXEC(@sql)

set @sql = 'UPDATE user_availableinventory SET [' + CAST(@counter AS nvarchar) + '] = @amount - @sum WHERE ID_User = ' +CAST(@userid AS nvarchar)

EXEC(@sql)

SET @counter = @counter + 1

END

这回Must declare the scalar variable "@amount".多次。 我知道这是一个丑陋的方法,对此问题的任何建议都非常感激。

回答:

您正在接收错误,因为您正在使用变量范围之外的变量。查询字符串作为单独的会话执行,因此您需要在查询字符串中声明变量。

可以通过声明的查询字符串

DECLARE @counter int 

DECLARE @userid int

declare @sql nvarchar(1000)

SET @counter = 0

SET @userid = 4

WHILE @counter < 500

BEGIN

set @sql = '

DECLARE @sum int

DECLARE @amount int

SELECT

@amount = [' + CAST(@counter AS nvarchar) + ']

FROM user_inventory WHERE ID_User = ' +CAST(@userid AS nvarchar)+'

SELECT

@sum = SUM([' + CAST(@counter AS nvarchar) + '])

FROM user_transactions WHERE ID_User = ' +CAST(@userid AS nvarchar)+'

UPDATE user_availableinventory SET [' + CAST(@counter AS nvarchar) + '] = @amount - @sum WHERE ID_User = ' +CAST(@userid AS nvarchar)

EXEC(@sql)

SET @counter = @counter + 1

END

以上是 SQL根据库存和交易计算余额 的全部内容, 来源链接: utcz.com/qa/264121.html

回到顶部