Click here to Skip to main content
16,007,163 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
UPDATE MembersTest 
   Set StudentID = CONCAT('S-000',[key])
   WHERE [key] = [key]


What I have tried:

Any solutions on how to increment a value using update without using the above code
Posted
Updated 18-Feb-19 23:07pm

That code doesn't increment anything: it sets a column value to a fixed string and an existing column value.
And there is a better way to do that anyway: Specify Computed Columns in a Table - SQL Server | Microsoft Docs[^] Use that, and the column data doesn't need to be stored or updated at all - saving space - and can be retrieved at any time using a normal SELECT.

But incrementing values via an UPDATE in a DB are a bad idea: they lead to intermittent an difficult to find problems in production because at some point two or more users will try to update to the same value for different rows - and your data will become compromised as a result. Instead of manually incrementing values, use an IDENTITY column, and let SQL sort it out for you - you don't need to know a student ID before the data is stored in the DB anyway - honest! IDENTITY (Property) (Transact-SQL) - SQL Server | Microsoft Docs[^]
 
Share this answer
 
Comments
CaptainChizni 19-Feb-19 2:46am    
Anyway, any solutions on how to increment a varchar?
OriginalGriff 19-Feb-19 2:58am    
Simple: don't. VARCHAR and NVARCHAR values aren't numeric, so they don't have a concept of "increment" or "decrement": only numeric fields have that.

The only way to increment one would be to convert it to a numeric type, increment that, and convert it back - and that implies that your DB design is faulty as you should be storing values in the *appropriate* datatype: numbers in numerics, dates in DATE, DATETIME, or DATETIME2, and only true strings in VARCHAR or NVARCHAR - to do otherwise is a recipe for later complexity and failures as the field will at some point contain "bad data".
Regardless of how much simpler it is to "just use VARCHAR throughout" it gives you problems later that are really nasty to sort out and increases the complexity of everything you do with your data later.
Although Griff is right, another option would be to use a SEQUENCE, see explanation here: CREATE SEQUENCE (Transact-SQL) - SQL Server | Microsoft Docs[^]

You can CAST the sequence number to varchar like this:
CAST(NEXT VALUE FOR MySequence AS NVARCHAR(10))
 
Share this answer
 
v2

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