具有自动生成字符的SQL标识

时间:2013-11-12 09:03:20

标签: sql sql-server

我有下表:使用SQL Server

create table PoojaDetails
(
    PoojaDetailsID int identity constraint pk_PoojaDetailsID Primary Key, 
    ReceiptNo AS 'PB' + '/' + datepart(yy,getdate()) + '/' + RIGHT('000000' + CAST(PoojaDetailsID AS VARCHAR(10)), 6) PERSISTED,
    ReceiptDate datetime not null constraint df_ReceiptDate default getdate(),
    FirstName varchar(100) not null,
    LastName varchar(100) not null,
    TelNo bigint
)

当我执行查询时:计算列' ReceiptNo'在表格' PoojaDetails'无法持久化,因为该列是非确定性的。

我希望将ReceiptNo设为:PB /年/不 例如; PB /二十一万三千四百三十三分之一十三

任何想法???谢谢你的时间

2 个答案:

答案 0 :(得分:1)

如果你可以依赖ReceiptDate总是被其默认约束填充而永不改变,那么你可以在计算列中使用它而不是getdate()

create table PoojaDetails
(
    PoojaDetailsID int identity constraint pk_PoojaDetailsID Primary Key, 
    ReceiptNo AS 'PB' + '/' + CONVERT(varchar(5),datepart(yy,ReceiptDate)) + '/' + RIGHT('000000' + CAST(PoojaDetailsID AS VARCHAR(10)), 6) PERSISTED,
    ReceiptDate datetime not null constraint df_ReceiptDate default getdate(),
    FirstName varchar(100) not null,
    LastName varchar(100) not null,
    TelNo bigint
)

答案 1 :(得分:1)

请尝试一下,

create table PoojaDetails
(
    PoojaDetailsID int identity constraint pk_PoojaDetailsID  Primary Key, 
    ReceiptNo  AS 'PB' + '/' + cast(datepart(yy,getdate()) as varchar(25)) + '/' + RIGHT('000000' + CAST(PoojaDetailsID AS VARCHAR(10)), 6) ,
    ReceiptDate datetime not null constraint df_ReceiptDate default getdate(),
    FirstName varchar(100) not null,
    LastName varchar(100) not null,
    TelNo bigint
)