【问题标题】:How do i set a temp variable to a value based from another table如何将临时变量设置为基于另一个表的值
【发布时间】:2014-10-24 20:53:34
【问题描述】:

我正在使用 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)

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

【问题讨论】:

  • 有什么问题?你有错误吗?你收到的价值不是你所期望的吗?我们需要一些工作。
  • 变量不会取值没有错误只是空值
  • 这条语句“select AccountID from TransID = @TranID”返回了多少
  • 我得到 1,值为 7 in,AccountID = 2
  • 你能再清楚一点我没有得到最后的评论

标签: sql join sql-server-2012


【解决方案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,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) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-23
    • 2011-05-21
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 2019-05-23
    • 1970-01-01
    相关资源
    最近更新 更多