Click here to Skip to main content
15,905,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How would I update the last two numbers in SQL.

Ex:
249691268200209200209

into:
249691268200209200231

What I have tried:

I just know how to select the data that ends with the tail end of those number I do not understand how to update the number.

SELECT data from data_table where data = '%0209';

I'm assuming:
UPDATE data_table set data = '%0231' WHERE data = '%0209';
Posted
Updated 26-Mar-20 22:45pm

We can solve it using the SUBSTRING Like the following update query :
UPDATE data_table
SET data = SUBSTRING(data, 1, LEN(data) - 2) + '31';

We can also permorm this query using replace method with Substring
UPDATE data_table
SET data = REPLACE(data, SUBSTRING(data, (LEN(data)-2),(LEN(data)+2)),'31')
 
Share this answer
 
Comments
Richard Deeming 27-Mar-20 8:46am    
Your first option is precisely what I posted in the comments three weeks ago.

Your second option is just wrong for a couple of reasons.
- The third argument to substring is the number of characters to return, not the index of the last character to return.
- If the last two digits appear anywhere else in the string, all instances will be replaced.

If you look at the example given in the question:
249691268200209200209249691268200209200231
Your second example would incorrectly change the value to:
2496912682003120031
A couple of options spring to mind:
SQL
UPDATE
    data_table
SET
    data = STUFF(data, Len(data) - 1, 2, '31')
WHERE
    data Like '%0209'
;
Or:
SQL
UPDATE
    data_table
SET
    data = Left(data, Len(data) - 2) + '31'
WHERE
    data Like '%0209'
;
NB: You need to use Like to match the pattern; otherwise, you'll only update records where the value is exactly equal to the string '%0209'.

STUFF (Transact-SQL) - SQL Server | Microsoft Docs[^]
LEFT (Transact-SQL) - SQL Server | Microsoft Docs[^]
LIKE (Transact-SQL) - SQL Server | Microsoft Docs[^]
 
Share this answer
 
Comments
Maciej Los 3-Mar-20 16:43pm    
5ed!

What about right and substring functions?
:D
Richard Deeming 4-Mar-20 7:36am    
Substring would work:
Substring(data, 1, Len(data) - 2) + '31'

Right wouldn't. :)
Maciej Los 4-Mar-20 7:53am    
;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900