简体   繁体   English

SQL Server在同一条语句中一起使用Convert和Replace

[英]Sql Server using Convert and Replace together in the same statement

I wanted to double check my logic for a query in SQL Server. 我想仔细检查我在SQL Server中查询的逻辑。

The idea is that I am able to feed the following values and it will make sure the result is a decimal with four trailing digits. 我的想法是能够输入以下值,并确保结果是带有四个尾随数字的十进制数。

Possible values for @LABORQTY : @LABORQTY可能值:

1,200

1,200.42

1200 (Integer)

1200.42

1200 (As a String)

1200.42 (As a String)

When the value is a string, it will give the error: Error converting data type nvarchar to numeric. 当该值为字符串时,将出现错误: Error converting data type nvarchar to numeric.

Here is my code: 这是我的代码:

CONVERT(DECIMAL(12, 4), REPLACE(@LABORQTY, ',', ''))

The output each time though should be decimal: 1200.4200 每次输出应为十进制:1200.4200

Your question is really confused, but I'll answer according to the following parameters: 您的问题确实很困惑,但是我将根据以下参数回答:

@laborqty is a VARCHAR @laborqty是VARCHAR

@laborqty may somehow come to contain any of the following values: @laborqty可能以某种方式包含以下任何值:

'1200'
'1200.42'
'1,200'
'1,200.42'

In which case CONVERT(DECIMAL(12, 4), REPLACE(@LABORQTY, ',', '')) will indeed produce a decimal with up to 4 digits of fractional precision. 在这种情况下, CONVERT(DECIMAL(12, 4), REPLACE(@LABORQTY, ',', ''))的确会产生一个小数,其精度最高为4位数字。 Whether your query tool/programming language will output it as 1200.4200 or not is another matter entirely; 您的查询工具/编程语言是否将其输出为1200.4200,完全是另一回事。 it might well just output 1200.42 and drop the trailing zeroes 它可能只输出1200.42并删除尾随零

If you're getting Error converting data type varchar to numeric. 如果Error converting data type varchar to numeric.遇到Error converting data type varchar to numeric. still, there is some other character data (not comma) in your numeric string 仍然,您的数字字符串中还有一些其他字符数据(非逗号)

If you definitely want the trailing zeroes, format it into a string before you output 如果您确实想要尾随零,请在输出之前将其格式化为字符串

FORMAT(CONVERT(decimal(12,4), '1200.42'), '0.0000')

This will generate a string with 4 trailing zeroes 这将生成一个带有4个尾随零的字符串

您可以使用 :

select CAST ( REPLACE( '1,200.4' , ',','') AS decimal(17,4))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM