问题
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