Is there a way to set primary key auto increment, type of varchar in mySql?
-
2What do you mean by auto-incrementing a varchar? – Sayan Dec 26 '12 at 09:36
-
An auto increment field should be `INT` – Shiridish Dec 26 '12 at 09:37
-
Possible duplicate of http://stackoverflow.com/questions/3455557/mysql-how-to-use-varchar-as-auto-increment-primary-key – Shiridish Dec 26 '12 at 09:37
-
Check this [possible duplicate](http://stackoverflow.com/questions/4699591/how-to-autoincrement-varchar) question in Stackoverflow. – Zeina Dec 26 '12 at 09:41
-
@Zeina Thanks for your link. – Ye Wint Dec 26 '12 at 09:47
-
Maybe you better look this link anyway, that a same question telling about.. http://stackoverflow.com/questions/4699591/how-to-autoincrement-varchar – Yanuar Dec 26 '12 at 09:38
4 Answers
NONE. So far, AUTO_INCREMENT can be set for INT only. It needs to have your own logic to do that. eg,
- Get Last ID
- Get the INT part within the string
- Increment the value
- Concatenate
- Save to DB
- 249,283
- 65
- 481
- 481
Duplication of MySQL - how to use VARCHAR as AUTO INCREMENT Primary Key
According to my point of view you have to change it as integer type.
Since AUTO_INCREMENT is for INT type only, moreover setting the field as PRIMARY KEY which prevents duplication of values.
- 1
- 1
- 20,245
- 6
- 62
- 74
AutoIncrement fields are integer in mysql.
You can mirror the auto-increment field in a varchar field and create a trigger which updates the varchar field on insert/update.
- 15,264
- 3
- 40
- 61
for my experience, you can make Varcar ID as auto increment but you must have logic..let say
Dim crnum As String = "CR00001"
Dim iTemp As Integer = 0
iTemp = CInt(crnum.Substring(4, crnum.Length - 4)) '// get only the #'s from String and Convert them to Integer.
iTemp += 1 '// increase the ID # + 1.
crnum = crnum.Substring(0, 4) & iTemp.ToString("00000") '// set the ID back with String and #'s formatted to 5 digit #.
but you must do your own logic ,because after u run it for second time it will become duplicate primary key so, you must think your logic to apply your code. Anything is possible. ;)
- 108
- 1
- 3
- 13