SQL查询转换

时间:2011-12-02 10:19:22

标签: sql

这绝对没问题

Update TradeFlow 
set flt_TotalPriceUSD= 
(Select top 1 (flt_ExRate * TradeFlow.flt_TotalPrice) 
from ExchangeRate ex inner join DateConversion dc 
on ex.dtm_Date = dc.gDate and  pDate=Convert(varchar,'01') + '/' 
+  Convert(varchar,'03') + '/' + Convert(varchar,'1389'))

但是当我用数据库中的值(TradeFlow.int_MonthTradeFlow.int_Year)替换它时,它就会停止工作。 pdate是一个字符串

Update TradeFlow 
set flt_TotalPriceUSD = (Select top 1 (flt_ExRate * TradeFlow.flt_TotalPrice)
from ExchangeRate ex inner join DateConversion dc   
on ex.dtm_Date = dc.gDate and  pDate=Convert(varchar,'01') + '/' +  
Convert(varchar,TradeFlow.int_Month) + '/' 
+ Convert(varchar,TradeFlow.int_Year))

任何想法为什么?

2 个答案:

答案 0 :(得分:2)

我的建议:

而不是:

Convert(varchar,TradeFlow.int_Month) ...
Convert(varchar,TradeFlow.int_Year))

写:

right( '0' + rtrim(ltrim(str(TradeFlow.int_Month))), 2) ...
right( '0000' + rtrim(ltrim(str(TradeFlow.int_Year))), 4) ...

答案 1 :(得分:2)

Update TradeFlow 
set flt_TotalPriceUSD= (Select top 1 (flt_ExRate * TradeFlow.flt_TotalPrice) 
    from ExchangeRate ex inner join DateConversion dc   
on ex.dtm_Date = dc.gDate and  
    --if pDate is varchar type (`dd/MM/yyyy`)
    pDate= '01/' + right('0' + cast(TradeFlow.int_Month as varchar), 2) + '/' + 
        cast(TradeFlow.int_Year as varchar)

    --if pDate is datetime type
    pDate=  cast(TradeFlow.int_Year as varchar) + 
        right('0' + cast(TradeFlow.int_Month as varchar), 2) + '01'