简体   繁体   English

如何在 SQL 中将 nvarchar 转换为十进制

[英]How to convert nvarchar to decimal in SQL

How to convert an nvarchar to decimal in SQL Server?如何在 SQL Server 中将 nvarchar 转换为十进制?

I need to convert a value like '38,716.1311' to 38716.1311.我需要将“ '38,716.1311'类的值转换为 38716.1311。

I have tried using this method but can't successfully convert:我曾尝试使用此方法但无法成功转换:

DECLARE @TempValue NVARCHAR(100) = '38,716.1311'

SELECT 
    CONVERT(DECIMAL(18, 2), @TempValue) 

Can anyone suggest the correct query?谁能建议正确的查询? Thanks in advance提前致谢

只需在转换前从字符串中删除逗号:

Select CONVERT(DECIMAL(18,2),replace('38,716.1311', ',', '')) 
Declare @TempValue nvarchar(100)
    SET @TempValue = Replace('38,716.1311',',','')
Select cast(@TempValue AS DECIMAL(18,2)) 

--we can not convert value Like "38,716.1311" (NVARCHAR) To DECIMAL so first we replace "," with blank "38716.1311" then convert with DECIMAL -- 我们不能将像 "38,716.1311" (NVARCHAR) 这样的值转换为 DECIMAL 所以首先我们用空白 "38716.1311" 替换 "," 然后用 DECIMAL 转换

Remove the comma by using REPLACE like so:使用 REPLACE 删除逗号,如下所示:

Declare @TempValue nvarchar = '38,716.1311'
Select CONVERT(DECIMAL(18,2), REPLACE(@TempValue, ',', ''))

Its better if the @TempValue is MONEY so it disregard the comma separated如果@TempValueMONEY则更好,因此它会忽略逗号分隔

Declare @TempValue MONEY =  '38,716.1311'
Select CAST(@TempValue AS DECIMAL(18,2))

Use MONEY data type and convert into decimal data type:使用 MONEY 数据类型并转换为十进制数据类型:

DECLARE @Col MONEY = '38,716.1311'
SELECT CONVERT(DECIMAL(20,4),@Col) 

OR Replace comma and convert into decimal或替换逗号并转换为十进制

DECLARE @Col VARCHAR(100)  = '38,716.1311'
SELECT CONVERT(DECIMAL(20,4),REPLACE(@Col,',',''))

In my case for example some data like: version: '1.2.12'以我为例,一些数据如下: version: '1.2.12'

I want to register like version: 1.212 in Sql我想在Sql中注册类似版本:1.212

  1. Clean the varchar ( eliminate dot or commas )清理varchar (消除点或逗号)

  2. Cast to char (6 digit) and pad with 0 the empty spaces.转换为字符(6 位)并用 0 填充空格。 (Catch null with coalesce) (使用合并捕获空值)

  3. Cast to numeric and divide to 100000转换为数字并除以 100000

  4. Cast to decimal (10,4)转换为十进制(10,4)

Result ->> version 1.212结果 ->> 版本 1.212

Select 'version'=cast(cast(replace(cast(replace(coalesce([##DATA##],'0'), '.', '') as char(6)),' ','0')as numeric(6))/100000 as decimal (10,4)

Maybe there is another solution which is more simple.也许还有另一种更简单的解决方案。

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

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