2

今天我想知道为什么这些简单的sql语句返回错误而不是成功执行:

GO
SELECT CAST('1,234.00' AS DECIMAL(22,2))
GO
SELECT CONVERT(DECIMAL(22,2), '1,234.00')

如果我删除千位分隔符,我发现脚本执行成功。

GO
SELECT CAST('1234.00' AS DECIMAL(22,2))
GO
SELECT CONVERT(DECIMAL(22,2), '1234.00')

所以问题是为什么 sql server 不接受千位分隔符作为输入?

此外,我发现相同的逻辑在 C# 中成功执行。

static void Main(string[] args)
{
    string s = "1,234.00";
    Console.WriteLine(decimal.Parse(s)); // result 1234.00
}

为什么他们对铸造对象有不同的政策?我已经在 C# 中验证了字符串,并且验证效果很好。但是,当我将字符串加载到 sql server 中时,我得到了错误。

4

3 回答 3

3

Try converting via money instead.

declare @d decimal(10,2)
SELECT @d = CAST('1,234.00' AS money)
select @d
GO
SELECT CONVERT(money, '1,234.00')

will give

1234.00
1234.00

Similarly

declare @m money = 1234
select CONVERT(varchar(20), @m, 1)

gives

1,234.00

See http://msdn.microsoft.com/en-us/library/aa226054(v=sql.80).aspx

于 2013-07-30T08:36:48.590 回答
0

SQL Server's CONVERT is not as versatile as .net's Parse.

  • If you use an SQL Server version prior to 2012, you might have to manually remove the thousands separators (using REPLACE).

  • Starting with SQL Server 2012, you can use the PARSE method, which seems to use the .net methods internally. In particular, when converting to decimal, it uses NumberStyles.Number, which includes AllowThousands. The following statement will return the correct value:

    SELECT PARSE('1,234.00' AS decimal(22,2) USING 'en-us')
    
于 2013-07-30T08:37:23.767 回答
-1

据我所知,十进制不能使用千位分隔符。对您来说最好的解决方案是先转换为货币,然后再转换为十进制。

SELECT CONVERT(decimal(22,2), CONVERT(money, '1,234.00'))

或更简单的钱

SELECT CONVERT(money, '1,234.00')
于 2013-07-30T08:46:59.447 回答