我想在具有标识列
的表中插入多行我有一个名为'STU'
的表,其中包含以下列:
SECTION(非null)
CREATE TABLE STU (SNO INT IDENTITY (1,1) CONSTRAINT PK_SNO PRIMARY KEY (SNO),
NAME VARCHAR(25), CLASS VARCHAR(20), SECTION CHAR );
在为每一行单独执行插入查询时插入值
INSERT INTO STU VALUES('A','1','A');
INSERT INTO STU VALUES('B','2','B');
INSERT INTO STU VALUES('C','3','C');
INSERT INTO STU VALUES('D','4','D');
INSERT INTO STU VALUES('E','5','E');
但是在尝试使用单个插入查询在每个可能的镜头中插入多个值时,它会抛出错误
INSERT INTO STU (SNO,NAME,CLASS,SECTION)
VALUES(NULL,NULL,NULL,NULL)
,('A','B','C','D','E','F')
,('1','2','3','4','5','6')
,('A','B','C','D','E','F');
也
INSERT INTO STU (NAME,CLASS,SECTION) VALUES
('A','B','C','D','E','F'),
('1','2','3','4','5','6'),
('A','B','C','D','E','F');
也
INSERT INTO STU (NAME,CLASS,SECTION) VALUES
('A','1','A'),
('B','2','A'),('C','3','A'),
('D','4','D'),
('E','5','E'),
('F','6','F');
也
INSERT INTO STU (SNO,NAME,CLASS,SECTION) VALUES
(NULL,'A','1','A'),
(NULL,'B','2','A'),
(NULL,'C','3','A'),
(NULL,'D','4','D'),
(NULL,'E','5','E'),
(NULL,'F','6','F');
答案 0 :(得分:1)
所有的插入语句都不好:
以下是一个例子:
INSERT INTO STU (NAME,CLASS,SECTION) VALUES
('A','B','C'),
('1','2','3'),
('A','B','C');
答案 1 :(得分:0)
您可以将其写为:
INSERT INTO STU VALUES
('A','1','A'),
('B','2','B'),
('C','3','C'),
('D','4','D'),
('E','5','E');
答案 2 :(得分:0)
您只需要连接第一个示例中的SQL。
您无法插入标识列(除非您当然转为标识插入)。
INSERT INTO STU (NAME,CLASS,SECTION)
VALUES
('A','1','A'),
('B','2','A'),
('C','3','A'),
('D','4','D'),
('E','5','E'),
('F','6','F');
如果您确实希望打开身份插入,则需要执行以下操作:
SET IDENTITY_INSERT STU ON
INSERT INTO STU (SNO, NAME,CLASS,SECTION)
VALUES
(1, 'A','1','A'),
(2, 'B','2','A'),
(3, 'C','3','A'),
(4, 'D','4','D'),
(5, 'E','5','E'),
(6, 'F','6','F');
SET IDENTITY_INSERT STU OFF
答案 3 :(得分:0)
如果您使用的是SQL Server 2005,请使用UNION ALL
INSERT STU (NAME,CLASS,SECTION)
SELECT 'A' AS NAME,'1' AS CLASS, 'A' AS SECTION
UNION ALL
SELECT 'B', '2', 'B'
UNION ALL
SELECT 'C', '3', 'C'
2005年以后的版本,您可以使用
INSERT STU (NAME,CLASS,SECTION)
VALUES ('A','1','A'),
('B','2','B'), ...