View Full Version : Giúp mình với : Tự tăng 01 field tring DB
Mình có 01 DataBase : "Ranger_DataBase" trong đó có một số table: Employee,Orders...
table Employee
{
empID nvarchar(15),<primary_key>
empFirstName(50),
empLastName(50),
.......
}
Minh muốn khi insert new Employee thì empID sẽ tự động tăng lên ví dụ: khi empID đang = EM001 thì sau khi insert new Employee thì empID sẽ tự tăng lên thành empID= EM002.Việc tăng lên này diễn ra trong DataBase.(Mình bên Code nên không rành DataBase lắm rất mong các bạn giúp đỡ) Cám ơn nhiều !!!
phatnq2003
15-05-2004, 23:48
Tự động trong database thì không có đâu, trừ khi field đó có kiểu số nguyên và có khái báo IDENTITY (tăng tự động - AutoNumber)
Còn theo như bạn thì tốt nhất là sử ở Code thôi nhưng bạn có thể "móc" max EmployeeID từ database và xử lý tăng dần theo ý bạn.
sontinh2004
19-06-2004, 14:05
Mình có 01 DataBase : "Ranger_DataBase" trong đó có một số table: Employee,Orders...
table Employee
{
empID nvarchar(15),<primary_key>
empFirstName(50),
empLastName(50),
.......
}
Minh muốn khi insert new Employee thì empID sẽ tự động tăng lên ví dụ: khi empID đang = EM001 thì sau khi insert new Employee thì empID sẽ tự tăng lên thành empID= EM002.Việc tăng lên này diễn ra trong DataBase.(Mình bên Code nên không rành DataBase lắm rất mong các bạn giúp đỡ) Cám ơn nhiều !!!
Vinasad - phatnq2003 noi co ly lam. Neu EmpID cua ban la EM***xx, ban co the suy nghi chi sai ***x (dung identity) cho column nay - co the ban se khong gap nhieu phien phuc. Neu EmpID co the co dang khac, ban co the lam nhu phatnq2003 da noi, which requires some additional coding.
If you must, you can use Instead Of insert (required sql2k).
Here is an example.
create table tb(empid char(6) primary key, empname sysname)
go
create trigger _tr on tb
instead of insert
as
declare @i int
select @i=isnull(count(*)+1,1) from tb
insert tb(empid,empname)
select 'emp'+right(1000+@i,3),empname
from inserted
go
insert tb select '999','abc'
insert tb select '999','def'
insert tb select '999','hig'
go
select * from tb
Powered by vBulletin® Version 4.2.0 Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.