日期:2014-05-17 浏览次数:20438 次
CREATE TABLE #tmp (id INT, Cname VARCHAR(20), Cnewid INT)
INSERT #tmp ( id, Cname, Cnewid )
SELECT 1, 'ab', NULL UNION ALL
SELECT 2, 'cd', NULL UNION ALL
SELECT 3, 'ab', NULL UNION ALL
SELECT 4, 'cd', NULL UNION ALL
SELECT 5, 'ab', NULL
;WITH cte AS
(
SELECT Cnewid,ROW_NUMBER() OVER(ORDER BY id) AS RN
FROM #tmp
)
UPDATE cte SET Cnewid=CASE RN%2 WHEN 1 THEN 1 ELSE 2 end
SELECT * FROM #tmp
if object_id('[tableA]') is not null drop table [tableA]
go
create table tableA(ID int,NAME char(20),newid int)
insert into tableA
select 1,'ab',NULl union all
select 2,'cd',NULl union all
select 3,'ab',NULl union all
select 4,'cd',NULl union all
select 5,'ab',NULl
update tableA set newid=nn from tableA A left join
(select NAME,row_number() over(order by NAME) as nn from tableA group by NAME) B
on A.NAME=B.NAME
---------------
ID NAME newid
----------- -------------------- -----------
1 ab 1
2 cd 2
3 ab 1
4 cd 2
5 ab