![](/img/trans.png)
[英]how to add a field in my table that is auto_incremented from 001 to 999 besides its original ID
[英]How to add a new row at the beginning and and the serialNO. is auto_incremented so the new row gets "1" and likewise the rest id's also change?
首先,您需要将所有行的序列号加一,以便为新行腾出空间:
UPDATE noticepdf
SET `serialNo.` = `serialNo.` + 1
ORDER BY `serialNo.` DESC;
ORDER BY 使行从下到上更新; 否则顶行将从 1 增加到 2,这将失败,因为已经有一行是 2。
现在您可以插入行,将序列号指定为 1:
INSERT INTO noticepdf (`serialNo.`, ...) VALUES (1, ...);
其中...
替换为您的其他字段。
以上内容可以包含在存储过程中,如下所示:
DELIMITER $$
CREATE PROCEDURE insert_noticepdf (noticeNumber TEXT, pdf BLOB)
BEGIN
UPDATE noticepdf
SET `serialNo.` = `serialNo.` + 1
ORDER BY `serialNo.` DESC;
INSERT INTO noticepdf (`serialNo.`, noticeNumber, pdf)
VALUES (1, noticeNumber, pdf);
END$$
DELIMITER ;
Existing table table1 has autoincrement column id and create a temp table with same table structure and insert the value you want to insert at top and then insert all record from existing table table1
then drop table1 and rename temp table temp01 to table1
SELECT TOP 1000 [id]
,[name]
,[age]
FROM [Mydb].[dbo].[table1]
CREATE TABLE temp01 (
ID int NOT NULL IDENTITY(1,1)PRIMARY KEY,
[name] varchar(255) NOT NULL,
Age int
);
INSERT INTO temp01 values('d',40)
INSERT INTO temp01 (name,age) SELECT name,age FROM table1;
drop table table1
exec sp_rename 'temp01', 'table1'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.