SQL服务器 - 演员和DIVIDE(SQL Server - CAST AND DIVIDE)

2019-09-28 17:37发布

DECLARE @table table(XYZ VARCHAR(8) , id int)

INSERT INTO @table
SELECT '4000', 1
UNION ALL
SELECT '3.123', 2
UNION ALL
SELECT '7.0', 3
UNION ALL
SELECT '80000', 4
UNION ALL
SELECT NULL, 5

查询:

SELECT CASE 
         WHEN PATINDEX('^[0-9]{1,5}[\.][0-9]{1,3}$', XYZ) = 0 THEN XYZ
         WHEN PATINDEX('^[0-9]{1,8}$',XYZ) = 0 THEN CAST(XYZ AS decimal(18,3))/1000
         ELSE NULL 
       END
  FROM @table

这部分- CAST(XYZ AS decimal(18,3))/1000不分割值。

它给了我更多的零的个数小数点后而不是将其划分的。 (我甚至封闭在括号和尝试,但结果相同)。

Ex:2000/1000 = 2000.000000

难道我做错了什么吗? 是PATINDEX表达参数是否正确?

Expected result:
4.000
3.123
7.000
80.000

不要让我知道如果PATINDEX不使用正确的方法? 我试图检查其是否已经与3位小数否则我想1000分十进制。

Answer 1:

尝试这个..

DECLARE @table table(XYZ VARCHAR(8) , id int)

INSERT INTO @table
SELECT '4000', 1
UNION ALL
SELECT '3.123', 2
UNION ALL
SELECT '7.0', 3
UNION ALL
SELECT '80000', 4
UNION ALL
SELECT NULL, 5
UNION ALL
SELECT 'WTF',6

SELECT CASE 
     WHEN ISNUMERIC(XYZ) = 0 THEN NULL
     WHEN CHARINDEX('.',XYZ,0) < LEN(XYZ)-2 AND CHARINDEX('.',XYZ,0) > 0 THEN XYZ
     WHEN ISNUMERIC(XYZ) >0  then  convert(decimal(18,3),xyz) / 1000.000
     ELSE NULL
END
  FROM @table

产量

4.00000000000
3.12300000000
0.00700000000
80.00000000000
NULL
NULL

编辑 - 保持到小数点后3位的输出做到这一点

SELECT convert(decimal(8,3),CASE 
     WHEN ISNUMERIC(XYZ) = 0 THEN NULL
     WHEN CHARINDEX('.',XYZ,0) < LEN(XYZ)-2 AND CHARINDEX('.',XYZ,0) > 0 THEN XYZ
     WHEN ISNUMERIC(XYZ) >0  then  convert(decimal(18,3),xyz) / 1000.000
     ELSE NULL
END)
  FROM @table

注意(8,3)定义此,总精度8位,3点之后。

你不妨转换回VARCHAR(8)太



Answer 2:

试试这个,转换整个案件为十进制(18,3):

DECLARE @table table(XYZ VARCHAR(8) , id int)

INSERT INTO @table
SELECT '4000', 1
UNION ALL
SELECT '3.123', 2
UNION ALL
SELECT '7.0', 3
UNION ALL
SELECT '80000', 4
UNION ALL
SELECT NULL, 5


SELECT CONVERT(decimal(18,3),CASE --nothing changes within the CASE
                                 WHEN PATINDEX('^[0-9]{1,5}[\.][0-9]{1,3}$', XYZ) = 0 THEN XYZ
                                 WHEN PATINDEX('^[0-9]{1,8}$',XYZ) = 0 THEN CAST(XYZ AS decimal(18,3))/1000
                                 ELSE NULL 
                             END
              )
FROM @table

OUTPUT:

---------------------------------------
4000.000
3.123
7.000
80000.000
NULL

(5 row(s) affected)


Answer 3:

值除以1000将为您到小数点后多个零

5.3 / 1000 = .0053


Answer 4:

select xyz, ((case when charindex('.', xyz) > 0 then cast(xyz AS decimal(18,3))*1000
                   else cast(xyz AS decimal(18,3)) end))/1000
from #table


文章来源: SQL Server - CAST AND DIVIDE