如何将数据插入具有外键的表中

时间:2018-10-18 21:16:38

标签: sql-server

我有一个名为“客户和信用卡”的表。我正在尝试将数据插入客户表。我很困惑如何将数据插入客户,并且抛出错误

  

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

CreditCards

CREATE TABLE CreditCards
(
    CreditCardID INT IDENTITY(1,1) PRIMARY KEY,
    FirstName NVARCHAR(40) NOT NULL,
    MiddleName NVARCHAR(40),
    LastName NVARCHAR(40) NOT NULL,
    Brand NVARCHAR(40) NOT NULL,
    Bank NVARCHAR(40) NOT NULL,
    [Number] INT UNIQUE NOT NULL,
    DateofExpiration DATETIME NOT NULL,
    VerificationCode INT NOT NULL
);

Customer表:

CREATE TABLE Customers
(
    CustomerID INT IDENTITY(1,1) PRIMARY KEY,
    FirstName NVARCHAR(40) NOT NULL,
    MiddleName NVARCHAR(40),
    LastName NVARCHAR(40) NOT NULL,
    StreetAddress NVARCHAR(100) NOT NULL,
    [State] NVARCHAR(40) NOT NULL,
    Country NVARCHAR(40) NOT NULL,
    CellPhoneNumber NVARCHAR(40),
    EmailAddress NVARCHAR(120),
    CreditCardID INT FOREIGN KEY REFERENCES CreditCards(CreditCardID)
);

我正在尝试使用此语句将数据插入客户表

INSERT INTO Customers 
VALUES ('John', 'ba', 'Dock', '515 East Halliday Street', 'Idaho', 'United States of America', '2082203814', 'docjon@ss.org');

1 个答案:

答案 0 :(得分:1)

此错误与外键无关。

Customers表有10列,但是INSERT语句中只有8个值。您缺少CustomerIDCreditCardID值。

您应该在INSERT语句中明确列出要填充的列:

INSERT INTO Customers (FirstName, MiddleName, LastNamr, StreetAddress, [State] , Country, CellPhoneNumber, EmailAddress)
VALUES('John','ba','Dock','515 East Halliday Street','Idaho','United State of America','2082203814','docjon@ss.org');

您忽略的列将获得其默认值; CustomerID将使用IDENTITY功能自动填充,而CreditCardID将是NULL。如果要使用刚插入到CreditCardID表中的行的CreditCards,可以使用@@IDENTITY变量:

NSERT INTO Customers (FirstName, MiddleName, LastNamr, StreetAddress, [State] , Country, CellPhoneNumber, EmailAddress, CreditCardID)
VALUES('John','ba','Dock','515 East Halliday Street','Idaho','United State of America','2082203814','docjon@ss.org', @@IDENTITY);

即使您提供所有列,这也是一个好主意,因为您不会使语句依赖于表创建中列的顺序。这也使代码更易于理解,因为读者不必参考表规范即可知道每个值是什么。

顺便说一句,您在其中一个列名中有一个错字:LastNamr应该是LastName