SQLServer IDENTITY Column with text

后端 未结 8 642
南旧
南旧 2020-11-30 10:48

How would I create an IDENTITY column in SQLServer with text in the column?

Example:


ABCD-987065
ABCD-987066
ABCD-987067

相关标签:
8条回答
  • 2020-11-30 11:24
    CREATE TABLE BikeParts (
        BikeParts_GUID AS 'ABCD-' + RIGHT(REPLICATE('0', 8) + CONVERT(VARCHAR, BikePart_ID), 10),
        BikePart_ID INT IDENTITY(1, 1),
        BikePart_Name VARCHAR(100)
    )
    
    INSERT INTO BikeParts VALUES ('Break Cable')
    INSERT INTO BikeParts VALUES ('Seat Cover')
    INSERT INTO BikeParts VALUES ('Head Light')
    INSERT INTO BikeParts VALUES ('Tail Lamp')
    
    SELECT * FROM BikeParts
    

    0 讨论(0)
  • 2020-11-30 11:29

    You'd have to not use an IDENTITY column, but generated the ids/strings yourself.

    Far better to format the IDENTITY column for display instead, especially if the string part is constant for all records - makes indexing/querying more performance and saves on db space.

    If records may have a different string section (i.e. not all starting with "ABCD-"), then you could store that as a separate field.

    0 讨论(0)
提交回复
热议问题