SQLServer IDENTITY Column with text

后端 未结 8 732
南旧
南旧 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:06

    No but you can create your Select statement in such a way as to return the code you want:

    Select 'ABCD-' + Cast(IdColumn as varchar) as IdColumn From MyTable Where (....);
    

    This assumes that you have a column called IdColumn in your table and that the "IDENTITY" property has been set to "true". That is, highlight the field in the table designer of SQL Server Management Studio and you'll see a window for the properties at the bottom.

    If the 'ABCD' part may change, you could place this value in another field and then retrieve as so:

    Select PrefixField + '-' + Cast(IdColumn as varchar) as IdColumn From MyTable Where (....);
    

    You could, of course, create a View to do this for you or even a computed field as well. That way, the return value is built in to the query and you don't have to remember to enter all of this each time.

提交回复
热议问题