如何将临时变量设置为基于另一个表的值

时间:2014-10-24 20:53:34

标签: sql join sql-server-2012

我使用的是AdventureWorks 2012数据库,我对这个数据库感到非常难过,

到目前为止我已经

alter proc pName
(
@TranID int
)
as
declare @AccountID int
declare @Entered datetime
declare @Type char
declare @Amount money
declare @Service money
declare @WithdrawalDecrease smallint
declare @WithdrawalCount smallint

set @AccountID = (select AccountID 
                  from Transactions
                  where TransID = @TranID)

set @WithdrawalCount = (select WithdrawalCount 
                        from Accounts
                        inner join Transactions on Transactions.AccountID = Accounts.AccountID
                        where Transactions.AccountID = @AccountID)

但是变量取值我做错了什么?

1 个答案:

答案 0 :(得分:1)

语法

没有问题
SET @AccountID = (SELECT AccountID
                  FROM   Transactions
                  WHERE  TransID = @TranID)
SET @WithdrawalCount = (SELECT WithdrawalCount
                        FROM   Accounts
                               INNER JOIN Transactions
                                       ON Transactions.AccountID = Accounts.AccountID
                        WHERE  Transactions.AccountID = @AccountID) 

但是在这里你试图将AccountID设置为@AccountID for TransID = @ TranID。如果您的Transactions表有@TranID的多行,则最后插入的值将分配给该变量 因此,请尝试将top 1order by

一起使用
SET @AccountID = (SELECT top 1 AccountID
                  FROM   Transactions
                  WHERE  TransID = @TranID order by column)

SET @WithdrawalCount = (SELECT top 1 WithdrawalCount
                        FROM   Accounts
                               INNER JOIN Transactions
                                       ON Transactions.AccountID = Accounts.AccountID
                        WHERE  Transactions.AccountID = @AccountID order by column)