爲產品或者商品隨機生成6位數的數字編碼方案

--爲產品或者商品隨機生成6位數的數字編碼方案
--準備階段
--建立一個表,生成100000到999999順序編碼
create table #no
(
 id int
)
declare @id int 
set @id=1
while(@id<=999999)
begin
 insert into #no values(@id)
 set @id=@id+1
end
--建立隨機編碼表
create table RNo
(
 id int identity(1,1),
 no int
)
--插入隨機內容
insert into RNo(no) select id from #no order by NEWID()
--模擬商品表
create table Product
(
 ProductId int identity(1,1),
 ProductNO int,
 ProductName varchar(100)
 --其他字段
)
--插入產品表的時候,通過產品表的自增ID讀取對應的隨機數字編碼更新到產品表即可實現隨機的編碼生成。
--避免了程序生成隨機編碼引起的2個小問題
 --1.每次生成都要做重複檢查
 --2.後期隨機編碼容易重複,要繼續隨機生成。
--存在一個問題就是一旦刪除產品後,編碼將不能被再次使用。
declare @pid int
insert into Product(ProductName) values('土豆')
select @pid=SCOPE_IDENTITY()
--這裏注意需要檢查 rno 是否大於 999999 ,如果不夠了 需要繼續生成新的編碼(增位了)
update Product set ProductNO=(select no from rno where id=@pid) where ProductId=@pid
--檢查結果
select * from Product

--ProductId   ProductNO   ProductName
----------- ----------- ---------------------------------------------------------
--1           782264      土豆
--(1 行受影響)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章