Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

How to Use Auto Increment in Varchar data Type in PHP an MYSQL?

can anyone tell us how to use auto increment in varchar data type?

i have look for other question and people always ask to use interger or use trigger. but however this is my college's project that has a rule for us to use varchar.


Automatically generated based on last Product ID existing in the database Ex. If the latest Product ID is ‘PR004’, then the new id will be ‘PR005’

so, we must set auto increment in php right?can someone tell me how to use this?

thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

MYSQL 5.7.5:

You can accomplish the goal using Generated Columns and this.

Not tested

CREATE TABLE TEST ( 
     ProdID VARCHAR(20) AS CONCAT('PR','',PID) STORED,
    PID INT auto_increment)

For your convenience,

MSSQL:

The easiest method is to simply make a calculated column. It uses what is known as a "calculated" column in conjunction with an IDENTITY column.

    CREATE TABLE Test
             (
              ProdID AS CAST('PR'+RIGHT('000'+CAST(RowNum AS VARCHAR(3)),3) AS VARCHAR(30)) PERSISTED
             ,ProdName VARCHAR(30)
,RowNum INT IDENTITY(1,1) 
             );


  INSERT INTO Test (ProdName)
  SELECT 'Thread' UNION ALL
  SELECT 'Button Thread' UNION ALL
  SELECT 'Coat Thread';

  SELECT ProdID, ProdName FROM Test;

That returns the following (notice that the auto-increment worked):

 ProdID                         ProdName
 ------------------------------ ------------------------------
 PR001                          Thread
 PR002                          Button Thread
 PR003                          Coat Thread

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...