varchar列与十进制列

时间:2017-01-30 18:49:06

标签: sql sql-server tsql

我有以下表格

productinfo

ID|productname|productarea|productcost|productid

销售

ID|salesid|productid|

SALESDATA

ID|productid|productname|salestotal

我遇到问题的地方是:salesdata.salestotalvarchar列,可能有空值

salesdata.saletotalproductinfo.productcost列进行比较。

我可以做一个

cast(salesdata.saletotal as float(7)) > X 

它有效。我想做的是

cast(salesdata.saletotal as float(7)) > productinfo.productcost
where     
  sales.productid = salesdata.productid and 
  productinfo.productid = salesdata.productid

然而,当我这样做时,我收到一个错误:

  

将varchar类型转换为float

时出错

我发现this帖子类似,但无法获得任何其他列。我无法更改当前的数据库结构。

2 个答案:

答案 0 :(得分:1)

如果您使用的是sql server 2012及更高版本,则可以使用try_cast()try_parse()

try_cast(salesdata.saletotal as float)>productinfo.productcost

try_parse(salesdata.saletotal as float)>productinfo.productcost

在2012年之前,我会使用patindex('%[^0-9.-]%',salesdata.saletotal)=0来确定某些内容是否为数字,因为isnumeric()有点broken

e.g。 rextester:http://rextester.com/UZE48454

case when patindex('%[^0-9.-]%',salesdata.saletotal)>0 
       then null 
     when isnull(cast(salesdata.saletotal as float(7)),0.0) 
        > isnull(cast(productinfo.productcost as float(7)),0) 
      then 1 
     else 0 
     end

答案 1 :(得分:1)

您可以在 where子句中添加IsNumeric(),以检查salesdata.saletotal是否可以解析为浮动

SELECT
cast(salesdata.saletotal as float(7)) > productinfo.productcost
FROM Sales,Salesdata
WHERE     
sales.productid = salesdata.productid and 
productinfo.productid = salesdata.productid and
IsNumeric(salesdata.saletotal) =1

或者您可以使用Not Like (最好比IsNumeric)

salesdata.saletotal NOT LIKE '%[^0-9]%'   
相关问题