How do i set a temp variable to a value based from another table

大兔子大兔子 提交于 2019-12-11 07:53:20

问题


I am using the AdventureWorks 2012 database and I'm absolutely stumped on this one,

So far I have

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)

But the variable taking the value what am I doing wrong?


回答1:


There is nothing wrong with the syntax

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) 

But here you are trying to set AccountID to @AccountID for TransID =@TranID. If your Transactions table has more than one row for @TranID then the last inserted value will be assigned to the variable so try using top 1 with order 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) 


来源:https://stackoverflow.com/questions/26556097/how-do-i-set-a-temp-variable-to-a-value-based-from-another-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!