Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 update values with out using cursor

Author  Topic 

roshana
Starting Member

31 Posts

Posted - 2009-10-14 : 06:09:21
Hi All,

I have one table with the structure
Emp id ,Contact no ,Department ID
I have records in this table for Emp Id and Contact no fields (1000 rows)
I have to update the value of Department from 1 to 16 in a sequential order
eg
Emp1,014-89899256,1
Emp2,014-89899786,2
.....
.....
Emp16,014-89899786,16
Emp17,014-89899745,1
Emp18,014-89899744,2
Without using cursor can we update the value in Department ID field

Thanks
Roshan

sanoj_av
Posting Yak Master

118 Posts

Posted - 2009-10-14 : 06:29:25
Update <Table_name> Set DepartmentId=SrNo
From
(
Select
EmpId,
row_number() Over(order by empid) SrNo
From
<Table_name>
)A
Where
<Table_name>.EmpId=A.EmpId And
A.SrNo<=16
Go to Top of Page

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2009-10-14 : 07:10:12
[code]
update t1
set Department_ID=dt.num16
from your_table t1
join
(
select
case rn%16 when 0 then 16 else rn%16 end as num16,
Emp_id
from
(
select
row_number() over (order by Emp_id) as rn,
Emp_id
from your_table
)dt1
)dt
on dt.Emp_id = t1.Emp_id

[/code]


No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2009-10-14 : 08:31:10
or use method 3

http://sqlblogcasts.com/blogs/madhivanan/archive/2009/06/10/quirky-update-in-sql-server.aspx

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2009-10-14 : 08:36:29
Cool and quirky!
Added to my favorites...
Great madhi


No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2009-10-14 : 08:43:59
quote:
Originally posted by webfred

Cool and quirky!
Added to my favorites...
Great madhi


No, you're never too old to Yak'n'Roll if you're too young to die.


Thanks

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -