sqlserver 主鍵默認(rèn)值

建立函數(shù)

     Create function  CreateProduct_ID()   
     Returns   Varchar(16)   
     As   
    Begin   
        Declare   @S   Varchar(100) 
        declare @id varchar(20)
        declare @date varchar(8)
        select @date=convert(varchar,getdate(),112)
        declare @count int
        select @count=count(*) from test where substring(id,1,8)=@date
    if @count=0
       begin
     
        select @S = @date+'0001' 
        
       end
    else 
       begin

        select @id=cast(cast(substring(max(id),9,4) as int)+1 as varchar) from test where substring(id,1,8)=@date
        select @S = @date+right('000'+cast(cast(@id as int) as varchar),4) 
       
    
       end
    Return @S
End   
Go

調(diào)用方法

 CREATE TABLE [dbo].[test](
        [id] [varchar](20) NOT NULL  Default  dbo.CreateProduct_ID(),
        [name] [varchar](10) NULL
) ON [PRIMARY]

設(shè)置默認(rèn)值改進(jìn)版

  Create function  CreateProduct_ID2()   
     Returns   Varchar(30)   
     As   
    Begin   
        Declare   @S   Varchar(100) 
        declare @id varchar(20)
        
        set @id = (CONVERT([bigint],replace(replace(replace(replace(CONVERT([nvarchar](100),CONVERT([nvarchar](100),getdate(),(121)),0),':',''),'-',''),' ',''),'.',''),0)) 
    

        
        select @S = 'HJ'+ @id
       
    Return @S
     
End   
Go

刪除函數(shù)

Drop function CreateProduct_ID

主鍵自增

1.新建一數(shù)據(jù)表,里面有字段id,將id設(shè)為為主鍵

 create table tb(id int,constraint pkid primary key (id))
 create table tb(id int primary key )

2.新建一數(shù)據(jù)表,里面有字段id,將id設(shè)為主鍵且自動(dòng)編號(hào)

 create table tb(id int identity(1,1),constraint pkid primary key (id))
 create table tb(id int identity(1,1) primary key )

3.已經(jīng)建好一數(shù)據(jù)表,里面有字段id,將id設(shè)為主鍵

alter table tb alter column id int not null 
alter table tb add constraint pkid primary key (id)

4.刪除主鍵

Declare @Pk varChar(100);
Select @Pk=Name from sysobjects where      Parent_Obj=OBJECT_ID('tb') and xtype='PK';
if @Pk is not null
exec('Alter table tb Drop '+ @Pk)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容