我的桌子看起来像这样
Serial | Name | Age
------------------------
1 | Aby | 43
3 | Philip | 15
5 | Tom | 65
6 | Jacob | 33
7 | Matt | 13
11 | Jerom | 37
我需要更新此表,以便序列列中的所有价值必须继续,而不会有任何缺失值
Serial | Name | Age
------------------------
1 | Aby | 43
2 | Philip | 15
3 | Tom | 65
4 | Jacob | 33
5 | Matt | 13
6 | Jerom | 37
---------------------------
如何在单个更新查询
中实现此目的答案 0 :(得分:5)
你可以这样做:
;with T as (
select row_number () over (order by Serial) as RN, *
from yourtable
)
update T
set Serial = RN
答案 1 :(得分:1)
你应该这样做:
创建一个结构相同但Primary Key Identity
的新表:
CREATE TABLE [dbo].[Z_NEW_TABLE](
[SERIAL] [bigint] IDENTITY(1,1) NOT NULL,
[NAME] [varchar](MAX) NULL,
[AGE] [INT] NULL
CONSTRAINT [PK_Z_NEW_TABLE] PRIMARY KEY CLUSTERED
(
[SERIAL] ASC
)WITH (
PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
将数据插入新表格
INSERT INTO Z_NEW_TABLE (NAME, AGE)
SELECT NAME, AGE
FROM Z_OLD_TABLE
最后删除旧表并重命名新表
答案 2 :(得分:1)
create table #tmp ( id int, name varchar(100)).
insert into #tmp
select 1,'Kesavan'
union
select 3,'Suyambu'
union
select 5,'Mani'
union
select 7,'Mahesh'
您需要声明一些变量才能实现这一目标,
declare @Count int =1
update #tmp set @count = id =@count+1 where id != @count
答案 3 :(得分:0)
进行更新的另一种方法 -
CREATE TABLE #updatetable (Serial int, Name varchar(10), Age int)
insert into #updatetable
select 1, 'Aby', 43 union all
select 3, 'Philip', 15 union all
select 5 , 'Tom', 65 union all
select 6 , 'Jacob', 33 union all
select 7 , 'Matt' , 13 union all
select 11 , 'Jerom' , 37
update #updatetable
set Serial = rn
from (
select Serial,row_number() over(order by Serial) rn
from #updatetable
) a
inner join #updatetable b on a.Serial = b.serial
答案 4 :(得分:0)
PHP。来自新手的回答:
$first_data =mysql_query("SELECT * FROM table");
$total = mysql_num_rows();
if($total > 0){
for($i=1; $i <= $total; $i++){
$fd = mysql_fetch_array($first_data);
$update = mysql_query("UPDATE table SET serial='".$i."' WHERE Name='".$fd['Name']."'");
}
}