如何在msSQL中为标识列字符添加前缀

时间:2014-09-15 14:46:59

标签: sql sql-server

如何更改表的主要标识列以在数字前包含一个字母?我有一个名为vendor_master的表,其中包含主键VendorID,我希望将其存储为v1v2v3等等

CREATE TABLE [dbo].[vendor_master](
[vendorID] [int] IDENTITY(1,1) NOT NULL,
[Vname] [nvarchar](50) NOT NULL,
[Email] [nvarchar](50) NOT NULL,
[Mobile] [bigint] NULL,
[Landline] [bigint] NULL,
[Address] [nvarchar](max) NOT NULL,
[Pincode] [int] NOT NULL)

2 个答案:

答案 0 :(得分:0)

你实际上无法按照自己的要求行事。无论如何,没有理由在字段值的前面添加相同的字母。而是在SELECT语句中添加字母:

SELECT CONCAT('v', vendorID) AS VendorIDWithPrefix, Vname, Email, Mobile
FROM vendor_master

答案 1 :(得分:0)

如果您在表格中填写该字段非常重要,请尝试以下操作:

CREATE TABLE [dbo].[vendor_master]
  (
    [vendorID] [int] IDENTITY(1,1) NOT NULL,
    [Vname] [nvarchar](50) NOT NULL,
    [Email] [nvarchar](50) NOT NULL,
    [Mobile] [bigint] NULL,
    [Landline] [bigint] NULL,
    [Address] [nvarchar](max) NOT NULL,
    [Pincode] [int] NOT NULL,
    [VendorKey]  AS ('v' +CONVERT([varchar](10),[vendorID])) PERSISTED
  )

当然,这会在排序时产生一些奇怪的结果,因此您可以考虑用零填充数据以使其具有一致的长度:

CREATE TABLE [dbo].[vendor_master]
  (
    [vendorID] [int] IDENTITY(1,1) NOT NULL,
    [Vname] [nvarchar](50) NOT NULL,
    [Email] [nvarchar](50) NOT NULL,
    [Mobile] [bigint] NULL,
    [Landline] [bigint] NULL,
    [Address] [nvarchar](max) NOT NULL,
    [Pincode] [int] NOT NULL,
    [VendorKey]  AS ('v' +RIGHT('000000000' + CONVERT([varchar](10),[vendorID]),10)) PERSISTED
  )