我正在尝试将SQL Server中的值拆分为单位、数千、数百万和数十亿。值可以是负数也可以是正数,并且值没有设置字符数/数字数。我到了这一步:

所以这是我的代码:
UPDATE table
SET Units = RIGHT(CONVERT(VARCHAR(50),[Value]), 3)
UPDATE table
SET Thousands = Right(CONVERT(VARCHAR(50),[Value]), 6)
UPDATE table
SET Thousands = SUBSTRING(CONVERT(VARCHAR(50),Thousands), 1, 3)但是在这里我遇到了一个问题,好像我有一个数字‘1019242’,对于单位它工作在-> 242,但是对于数千,我首先想要从右边开始的6位数: 019242,然后是子字符串前3位,但是0正在消失,所以我得到192而不是19 ...
我也不知道如何处理数十亿,因为数字的大小可能会有所不同,所以可以是'19 105‘或'37 594 820 583’……
顺便说一句,这只是我想出来的方法,但也许有更容易做的事情!
提前感谢您的帮助!
我设法(感谢评论!,谢谢你)谈到了这一点:

现在,我正在尝试将结果保存到我的数千列。我不知道该怎么做,我正在查。
再次感谢您的帮助!
发布于 2018-10-24 16:18:03
整数数学和mod的混合应该可以得到你想要的东西。
SELECT A.Value,
ABS(A.Value) / 1000000000 AS Billions,
ABS(A.Value) % 1000000000 / 1000000 AS Millions,
ABS(A.Value) % 1000000 / 1000 AS Thousands,
ABS(A.Value) % 1000 AS Units,
CASE WHEN A.Value < 0 THEN -1 ELSE 1 END AS New_Col
FROM (
VALUES (CAST(3070192242 AS BIGINT)),(-370192242)
) AS A(Value);编辑:
更新语句:
UPDATE A
SET Billions = ABS(A.Value) / 1000000000,
Millions = ABS(A.Value) % 1000000000 / 1000000,
Thousands = ABS(A.Value) % 1000000 / 1000,
Units = ABS(A.Value) % 1000,
New_Col = CASE WHEN A.Value < 0 THEN -1 ELSE 1 END AS New_Col
FROM dbo.YourTable AS A;发布于 2018-10-24 16:19:50
请尝试以下操作:
update [table] set
[units] = abs([value] % 1000)
,[thousands] = abs([value] % 1000000 / 1000)
,[millions] = abs([value] % 1000000000 / 1000000)
,[billions] = abs([value] % 1000000000000 / 1000000000)
,[new_col] = sign([value])而且,如果您有日志文件增长问题,请尝试循环方法,它使用较少的日志空间:
while exists (select null from [table] where [units] is null)
begin
update top(1) percent [table] set
[units] = abs([value] % 1000)
,[thousands] = abs([value] % 1000000 / 1000)
,[millions] = abs([value] % 1000000000 / 1000000)
,[billions] = abs([value] % 1000000000000 / 1000000000)
,[sign] = sign([value])
where [units] is null
end;发布于 2018-10-28 03:31:53
另一种选择是使用计算字段。这些字段在数据库中使用no space,因此文件大小应该不是问题。并且您不需要设置或更新它们。
create table BigVal ( [Value] int,
Billions as abs([Value] / 1000000000 ),
Millions as abs([Value] % 1000000000 / 1000000),
Thousands as abs([Value] % 1000000 / 1000),
Units as abs([Value] % 1000),
[Sign] as case when Value < 0 then -1 else 1 end )
insert into BigVal ( [Value] ) values
( 234 ),
( 123456 ),
( 123456789 ),
( 1234567890 ),
( -23 ),
( -1234567890 ),
( 2147483647 ),
( -2147483648 )
select * from BigVal 结果是:
Value Billions Millions Thousands Units Sign
----------- ----------- ----------- ----------- ----------- -----------
234 0 0 0 234 1
123456 0 0 123 456 1
123456789 0 123 456 789 1
1234567890 1 234 567 890 1
-23 0 0 0 23 -1
-1234567890 1 234 567 890 -1
2147483647 2 147 483 647 1
-2147483648 2 147 483 648 -1https://stackoverflow.com/questions/52963670
复制相似问题