I want to generate a column with auto generated value in pattern of MMddyyyyhhmmss0001
Here 0001 is SEQUENCE value
After a lot of search I found a solution
CREATE SEQUENCE [dbo].[BikePartIdHelper]
AS [int]
START WITH 1
INCREMENT BY 1
MINVALUE 0
MAXVALUE 2147483647
CACHE
GO
CREATE TABLE [dbo].[BikeParts]
(
[ID] [INT] IDENTITY(1,1) NOT NULL,
[BikeParts_GUID] AS ((REPLACE(CONVERT([VARCHAR](10), GETDATE(),(101)), '/', '') + REPLACE(CONVERT([VARCHAR], GETDATE(), (8)), ':', '')) + RIGHT(REPLICATE('0', (4)) + CONVERT([VARCHAR], [BikePart_ID]), (4))) PERSISTED,
[BikePart_ID] [INT] NOT NULL,
[BikePart_Name] [VARCHAR](100) NULL,
CONSTRAINT [PK_BikeParts]
PRIMARY KEY CLUSTERED ([ID] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[BikeParts]
ADD DEFAULT (NEXT VALUE FOR [dbo].[BikePartIdHelper]) FOR [BikePart_ID]
GO
But I get this error from this code:
Msg 4936, Level 16, State 1, Line 11
Computed column 'BikeParts_GUID' in table 'BikeParts' cannot be persisted because the column is non-deterministic
Code is working fine if I remove PERSISTED
, but in that case it will generate new value in every select statement, So I need to make it as PERSISTED
.
It is not necessary to use computed column, If there are any alternatives for solving my purpose of generate value of column as MMddyyyyhhmmss0001
I will really thankful for any type of help.