Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sql auto counter

Status
Not open for further replies.

Deam

Programmer
Oct 10, 2000
68
0
0
US
I had converted some records in a SQL Server database - now I need to assign their ID fields numbers starting from 3100 to 3999. I know I have to do the Select part but how do I start numbering them ? and stop at 3999.

Update Tbl_Emp
SET EmpID = ?????????????????
WHERE EmpID = NULL


Appreciate any help.
 
Not sure if this is the best way, but it worked for me. First create an identity column on your table. Then try this code. After that, you can drop the identity column.
Code:
select * into #temp
from tbl_emp
where empid is null

declare @i int
declare @inc  int
declare @maxinc int
declare @bsid int

set @i = (select count(*) from #temp)
set @inc = 3100
set @maxinc = 3999
--This is the identity column (bsid)
set @bsid = (select min(bsid) from #temp)

while  @i > 0 AND @inc < @maxinc 
   begin
      update tbl_emp
      set empid = @inc
      where bsid = @bsid

      set @inc = @inc + 1
      delete from #temp where bsid = @bsid
      set @bsid = (select min(bsid) from #temp)
      set @i = (select count(*) from #temp)
   end

drop table #temp

Jim
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top