I am using Microsoft SQL Server 2014 and have a table with three columns and the field data type is Decimal(38,0)
.
I want to update each row of my table to insert a decimal point after the first two digits. For example, I want 123456
to become 12.3456
. The numbers are different lengths; some are five digits, some are seven digits, etc.
My table is:
+-------------+-------+-------+
| ID | X | Y |
+-------------+-------+-------+
| 1200 | 321121| 345000|
| 1201 | 564777| 4145 |
| 1202 | 4567 | 121444|
| 1203 | 12747 | 789887|
| 1204 | 489899| 124778|
+-------------+-------+-------+
And I want to change this to:
+-------------+--------+--------+
| ID | X | Y |
+-------------+--------+--------+
| 1200 | 32.1121| 34.5000|
| 1201 | 56.4777| 41.45 |
| 1202 | 45.67 | 12.1444|
| 1203 | 12.747 | 78.9887|
| 1204 | 48.9899| 12.4778|
+-------------+--------+--------+
My code is:
Update [dbo].[UTM]
SET [X] = STUFF([X],3,0,'.')
[Y] = STUFF([X],3,0,'.')
And I tried this:
BEGIN
DECLARE @COUNT1 int;
DECLARE @COUNT2 int;
DECLARE @TEMP_X VARCHAR(255);
DECLARE @TEMP_Y VARCHAR(255);
DECLARE @TEMP_main VARCHAR(255);
SELECT @COUNT1 = COUNT(*) FROM [UTM];
SET @COUNT2 = 0;
WHILE(@COUNT2<@COUNT1)
BEGIN
SET @TEMP_main = (SELECT [id] from [UTM] order by [id] desc offset @COUNT2 rows fetch next 1 rows only);
SET @TEMP_X = (SELECT [X] from [UTM] order by [id] desc offset @COUNT2 rows fetch next 1 rows only);
SET @TEMP_Y = (SELECT [Y] from [UTM] order by [id] desc offset @COUNT2 rows fetch next 1 rows only);
UPDATE [dbo].[UTM]
SET [X] = CONVERT(decimal(38,0),STUFF(@TEMP_X,3,0,'.'))
,[Y] = CONVERT(decimal(38,0),STUFF(@TEMP_Y,3,0,'.'))
WHERE [id] = @TEMP_main;
SET @COUNT2 = @COUNT2 + 1
END
END
decimal(38,0)
; that's a precision of 0; it can't store a value with any decimal points. Like i mentioned before (as well) your data seems far better suited to something like adecimal(6,4)
. – StaticsSTUFF
will count-
as a character, meaning that it isn't "always" the third character that needs to be the decimal point. – Statics