【问题标题】:Cannot convert a char value to money in SQL无法在 SQL 中将 char 值转换为货币
【发布时间】:2019-06-05 15:36:11
【问题描述】:

我有一个名为“companyInfo”的表,“Amount”的数据类型是nvarchar,示例数据如下所示:

公司信息

IDs | company   | year | Amount
----+-----------+------+-------
1   | Company A | 2011 | 40.00
2   | Company B | 2011 | Null
2   | Company C | 2011 | 100.00
4   | Company D | 2011 | 205.11
5   | Company E | 2011 | 0
6   | Company F | 2011 | Null

我写了如下查询:

select IDs
  , company
  , sum(ISNULL(CAST(Amount AS MONEY), 0)) Amount
  , year
from companyInfo 
where Amount is not null 
  and year(cast(year as date)) = '2018'
group by IDs
  , company
  , Amount
  , year

出现以下错误:

错误:
消息 235,第 16 级,状态 0,第 27 行 无法将 char 值转换为货币。 char 值的语法不正确。

【问题讨论】:

  • 使用 try_convert(money,...) 如果转换失败而不是抛出错误,它将返回 NULL。识别问题值 Select * from yourtable where try_convert(money,Amount) is null
  • 谢谢@JohnCappelletti,它通过使用“try_convert”起作用,不确定为什么我在使用 CAST 时出错

标签: sql sql-server database data-analysis


【解决方案1】:

这就是你想要的......两个查询提供相同的结果

样式 1

SELECT IDs
    ,Company
    ,FORMAT(YearFormed, 'yyyy') AS YearFormed
    ,Amount

FROM
(SELECT C.IDs, C.Company, CONVERT(DATE, C.YearFormed) AS YearFormed, CONVERT(MONEY, C.Amount) AS Amount FROM temp.dbo.CompanyInfo AS C) AS RC
WHERE Amount IS NOT NULL

样式 2

WITH RESULT AS --3-I named this query with the intention to formart the Year in which the companies were formed
(
SELECT IDs --1-Started from here
    ,Company
    ,CONVERT(DATE, C.YearFormed) AS YearFormed --2-I converted to Date here so I couldnt run format too so
    ,CONVERT(MONEY, C.AMOUNT) AS Amount
FROM temp.dbo.CompanyInfo AS C
WHERE C.AMOUNT IS NOT NULL
)
SELECT R.IDs 
    ,R.Company
    ,FORMAT(R.YearFormed, 'yyyy') AS YearFormed --4-I used this SELECT statement only to format this column
    ,R.Amount
FROM RESULT AS R

结果就是这样

【讨论】:

  • 谢谢@ZabiSidiqkhil,这很有帮助。
【解决方案2】:

可能是因为您的区域设置。 请检查:

select
     IDs
     ,company
     ,sum(ISNULL(CAST(REPLACE(Amount, '.', ',') AS MONEY),0)) Amount
     ,year

from companyInfo 
    where Amount is not null 
    and year(cast(year    as date)) = '2018' 
    group by IDs,company,Amount,year;

你可以通过运行来调试失败的原因:

SELECT CAST(REPLACE('205.11', '.', ',') AS MONEY),0)

或者

SELECT CAST('205.11'AS MONEY)

隔离问题

【讨论】:

  • 命令 dbcc useroptions 查看默认语言
猜你喜欢
  • 1970-01-01
  • 2022-12-03
  • 1970-01-01
  • 2022-01-17
  • 2020-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多