bestlong 怕失憶論壇

標題: MSSQL自動產生編號格式 [打印本頁]

作者: bestlong    時間: 2008-12-4 17:24     標題: MSSQL自動產生編號格式

怎樣由 SQL Server 2000 系統自動編號產生格式如:BV+YYYYMM+編號
BV是固定字串
YYYYMM是年月
編號是0到9的數字

使用觸發器來處理
  1. create table test(
  2. id varchar(20),
  3. sname varchar(20)
  4. )
複製代碼
  1. create TRIGGER [test_insert] ON [dbo].[test]
  2. INSTEAD OF Insert
  3. AS
  4. declare @str varchar(20)
  5. declare @i integer
  6. set @str = 'BV'+left(convert(char,getdate(),112),6)
  7. select @i=isnull(max(cast(right(rtrim(id),len(id)-8) as integer)),0) from
  8. (select id from test where id like @str+'%') a
  9. set @i=@i+1
  10. Insert INTO TEST
  11. Select @STR++cast(@i as char)as id,sname from inserted
複製代碼
上面建好後執行:
insert into test(sname) values('test')
id欄位就會自動編好號




歡迎光臨 bestlong 怕失憶論壇 (http://www.bestlong.idv.tw/) Powered by Discuz! X1.5