列名或提供的值的数量与表定义 sql 不匹配



在SQL Server中,我试图使用以下查询在表中插入值:

ALTER TABLE student ADD NrLeg_sot varchar(5)
INSERT INTO student 
VALUES ('117', 'Popescu', 'F', 'Florentina', 'f', CONVERT (smalldatetime, '15/04/1978', 103), 'C', '223', '102')

我有这张桌子:

DROP TABLE student;
CREATE TABLE student 
(
NrLeg int NOT NULL PRIMARY KEY,
Name varchar(20),
Initiala varchar(5),
Prenume varchar(20),
Grupa int,
Nota int,
CodDisciplina int ,
gen varchar(5),
DataS  datetime
); 

我得到以下错误:

列名或提供的值数与表定义不匹配。

为什么?

您有以下语句:

INSERT INTO student VALUES(
'117',     -- maps to NrLeg which has data type int
'Popescu', -- maps to Name
'F',       -- maps to Initiala
'Florentina', -- maps to Prenume
'f',       -- maps to Grupa, which is of data type int
CONVERT (smalldatetime,'15/04/1978',103), -- maps to Nota, also an int
'C',       -- maps to CodDiscipline, an int
'223',     -- maps to gen
'102'      -- maps to DataS, a datetime
)

IOW在您的插入语句中没有太多有效的内容。但是,如果添加列名列表(并调整数据类型(,数据库引擎就会知道如何将指定的值映射到列:

INSERT INTO student (NrLeg, Name, Initiala, Prenume, gen, DataS, Grupa, Nota,
CodDiscipline)
VALUES(
117,       -- maps to NrLeg which has data type int
'Popescu', -- maps to Name
'F',       -- maps to Initiala
'Florentina', -- maps to Prenume
'f',       -- maps to gen
CONVERT (smalldatetime,'15/04/1978',103), -- maps to DataS
'C',       -- maps to Grupa, an int, this is still a problem
223,       -- maps to Nota
102        -- maps to CodDiscipline
)

不过,您仍然会对值"C"有问题。

您可以匹配以下查询。您应该传递不带单引号的整列值。

此外,当您以以下格式化方式编写查询时,列计数的顺序和数量也很容易验证。

create table student (
NrLeg int NOT NULL PRIMARY KEY,
Name varchar(20),
Initiala varchar(5),
Prenume varchar(20),
Grupa int,
Nota int,
CodDisciplina int ,
gen varchar(5),
DataS  datetime
); 
ALTER TABLE student ADD NrLeg_sot varchar(5)
INSERT INTO student 
VALUES(117 --NrLeg
,'Popescu' --Name
,'F' --Initiala 
,'Florentina' --Prenume
, 0 --Grupa
, 0 --Nota
, 0 --CodDisciplina
,'C' --gen
,CONVERT (smalldatetime,'15/04/1978',103) --DataS
,'102' --NrLeg_sot
)
Select * from student

这是实时数据库<>小提琴演示。

在表中插入时,最好用括号传递列名,如下所示

INSERT INTO student (<column1 name>, <column2 name>, <column3 name>, ...)
Values(<column1 value>, <column2 value>, <column3 value>, ...)

最新更新