错误:为变量赋值的SELECT语句不能与数据检索操作结合使用

时间:2015-08-04 11:05:35

标签: sql-server

当我运行以下查询时,发生错误:

  

为变量赋值的SELECT语句不能是   结合数据检索操作。

我该如何解决这个问题?

以下是查询:

DECLARE @loanInstallmet float

SELECT TOP (1) 
    loan.loanID,members.offno AS OfficialNumber,
    loan.loanAmount,
    loan.interestRate,
    loan.NoOfInstallment,
    loanHistory.presentInstallmentNo,
    loanHistory.dateBalanceUpdate,
    (loanHistory.presentInstallmentNo + 1) AS InstallmentNo, 
    members.monthllyContribution AS MonthlyContribution, 
    @loanInstallmet = 
        CASE 
            WHEN  loan.remarks = 'Half' THEN ROUND(loanHistory.balanceAmount/ (loan.NoOfInstallment-loanHistory.presentInstallmentNo ), 0) 
            ELSE ROUND((loan.loanAmount / loan.NoOfInstallment), 0)
        END, 
    CASE 
        WHEN  loanHistory.presentInstallmentNo % 12 = 0 THEN ROUND(((loan.loanAmount-loanHistory.balanceAmount) * loan.interestRate / 1200), 0)
        ELSE ROUND((loan.loanAmount * loan.interestRate / 1200), 0)
    END AS MonthlyInterest, 
    LEFT(DATENAME(MONTH,Getdate()),3)as recMonth,
    year(GETDATE())as recYear,
    loan.isRecovered as LoanIsRecovered,
    members.memberIsActive,
    loanHistory.status,
    ROUND((loanHistory.balanceAmount-@loanInstallmet), 0) AS BalanceAmount,
    loan.remarks
FROM loan
INNER JOIN members 
    ON loan.offNo = members.offno
INNER JOIN loanHistory 
    ON members.offno = loanHistory.offNo
    AND loan.loanID = loanHistory.loanID
WHERE 
    loan.isRecovered = 0
    AND members.memberIsActive = 1  
order by loanHistory.presentInstallmentNo DESC

2 个答案:

答案 0 :(得分:1)

这是说它意味着什么! ;)

你无法做到:

SELECT TOP(1)loan.loanID,members.offno AS OfficialNumber,....

同时:

SELECT @loanInstallmet =例如,当loan.remarks =' Half'那么

您要么为应用程序检索数据,要么设置变量的值。同时做两者并不符合逻辑。

如果您想计算@loanInstallmet并在将来的计算中使用它,您可以执行以下操作:

x.indexOf("foo") > -1 //true

tblLoanInstallCalc是一个公用表表达式(CTE),在您尝试累加余额之前预先计算先决条件

答案 1 :(得分:0)

将SELECT语句中的列值分配给局部变量时会发生此错误,但并非所有列都分配给相应的局部变量。
要避免此错误,请确保将所有列分配给局部变量。

如果您确实需要同时执行这两个操作,意味着将值分配给局部变量并将列作为结果集返回,则必须分两步执行,而不是将它们组合到一个SELECT语句中:

DECLARE @CompanyName NVARCHAR(40)
DECLARE @ContactName NVARCHAR(30)

SELECT @CompanyName = [CompanyName],
       @ContactName = [ContactName],
FROM [dbo].[Customers]
WHERE [CustomerID] = 'ALFKI'

SELECT [ContactTitle]
FROM [dbo].[Customers]
WHERE [CustomerID] = 'ALFKI'

请阅读此article了解详情