我运行此查询时一直收到错误。有谁看到我搞砸了?

时间:2018-02-28 02:40:52

标签: sql sql-server

SELECT [property usage], 
       [total], 
       [todate], 
       [todateorder], 
       [purpose of loan], 
       [marital status], 
       [agegroup], 
       [race], 
       [sex], 
       Datepart(mm, loandate)                          LoanMonth, 
       Datepart(yy, loandate)                          LoanYear, 
       Avg(CONVERT(DECIMAL(10, 2), monthlyincome))     AvgMonthlyIncome, 
       Avg(CONVERT(DECIMAL(10, 2), loanamount))        AvgLoanAmount, 
       Sum(CONVERT(DECIMAL(10, 2), monthlyincome) / 
           CONVERT(DECIMAL(10, 2), loanamount) 
       )                                               MonthlyIncomeVSLoanAmount 
       , 
       @MTD                                            MTD, 
       @MonthlyPrior6mnthAvg                           MonthlyPrior6mnthAvg, 
       ( ( @MTD * 1.00 ) / @MonthlyPrior6mnthAvg ) * 100 
       MTDvsMonthlyPrior6mnth_Avg_PerInc, 
       @LastFullMonth                                  LastFullMonth, 
       @MonthlyPrior6mnthAvgExcludeCurrMonth 
       MonthlyPrior6mnthAvgExcludeCurrMonth, 
       ( ( @LastFullMonth * 1.00 ) / @MonthlyPrior6mnthAvgExcludeCurrMonth ) * 
       100 
       LastFullMonthvsMonthlyPrior6mnthExcludeCurrMonthAvg_PerInc, 
       @QTD                                            QTD, 
       @LastFullQuarter                                LastFullQuarter, 
       ( ( @QTD * 1.00 ) / @LastFullQuarter ) * 100    QTDvsLastFullQuarter, 
       ( Datename(month, loandate) + ' ' 
         + Datename(year, loandate) )                  ReportMonth, 
       [borrowername]                                  NAME, 
       loanamount, 
       [purchase price], 
       [monthlyincome], 
       Datename(month, loandate)                       MonthName, 
       ( [borrowername] + ' ' + '(' + [loan_id] + ')' )Name2 
  

Msg 245,Level 16,State 1,Procedure proc_LoansProcessed_ToDate,Line   178 [批处理开始第7行]转换varchar时转换失败   价值')'数据类型int。

3 个答案:

答案 0 :(得分:0)

我认为在连接[Loan_ID] +')时遇到错误。在

([BorrowerName]+' '+'('+[Loan_ID]+')') Name2

使用concat函数

答案 1 :(得分:0)

with open("somefile.py", encoding="utf-8") as f: exec(f.read()) 投射到loan_Id

varchar

( [borrowername] + ' ' + '(' + [loan_id] + ')' ) Name2 

[borrowername] + ' ' + '(' + [cast(loan_id as varchar(50))] + ')' as Name2 与任何int连接时,sql引擎会隐式将字符串转换为int,因为string的优先级高于int。因此,您需要明确地将varchar转换为loan_id以避免此问题

此外,我刚删除了不需要的括号,使代码看起来更清晰

答案 2 :(得分:0)

将查询的最后一行更改为 -

( [borrowername] + ' ' + '(' + CONVERT(NVARCHAR(10),[loan_id]) + ')' )Name2

注意 - 根据您的要求,在上面的行中替换NVARCHAR(10)。