如何将更新语句值添加到变量?

时间:2017-03-07 15:46:48

标签: sql sql-server

我想将数据保存在变量中,稍后在过程中使用它。

UPDATE  acc_Account
                SET     acc_Account.CompanyID = ( SELECT TOP 1
                                                          utl_Company.CompanyID
                                                  FROM    utl_Company
                                                  ORDER BY CompanyID DESC
                                                )
                WHERE   acc_Account.AccountNumber = @AccountNumber 

如何将CompanyID保存在变量中,以便稍后在插入语句中使用它?

3 个答案:

答案 0 :(得分:4)

在代码的开头有这个:

declare @var varchar(20) -- change the data type according to your needs
set @var = (SELECT TOP 1 utl_Company.CompanyID FROM utl_Company ORDER BY CompanyID DESC)

答案 1 :(得分:2)

在更新语句之前创建select local variable,然后设置它,然后使用它。

DECLARE @companyID INT;
SELECT @companyID = "YOUR QUERY";

答案 2 :(得分:1)

我认为有效的方法是使用OUTPUT子句

DECLARE @TAB TABLE (CompanyID BIGINT  )
UPDATE acc_Account
SET acc_Account.CompanyID = (
        SELECT max(CompanyID) FROM utl_Company
        )
output inserted.CompanyID into @TAB
WHERE acc_Account.AccountNumber = @AccountNumber

SELECT * FROM @TAB