我有兩個表,分別爲Questions
和Answers
,它們分別存儲多選題和4個可能的答案。我試圖一次插入一個問題及其4個答案。在sql中插入選擇題和答案
The INSERT statement conflicted with the FOREIGN KEY constraint .... "dbo.Answers", column 'AnswerID'.
The INSERT statement conflicted with the FOREIGN KEY constraint table "dbo.Questions", column 'QuestionID'.
這裏是我的表是這樣的:
CREATE TABLE [dbo].[Questions] (
[QuestionID] INT IDENTITY (1, 1) NOT NULL PRIMARY KEY,
[HistID] INT NOT NULL,
[Question] NCHAR (300) NOT NULL,
[AnswerID] CHAR NOT NULL,
FOREIGN KEY (AnswerID) REFERENCES [dbo].Answers (AnswerID),
FOREIGN KEY (HistID) REFERENCES [dbo].HistoricalEvents (HistID)
);
CREATE TABLE [dbo].[Answers] (
[QuestionID] INT NOT NULL,
[AnswerID] CHAR NOT NULL,
[Choice] NCHAR (200) NOT NULL,
FOREIGN KEY (QuestionID) REFERENCES [dbo].[Questions] (QuestionID),
PRIMARY KEY ([AnswerID])
);
這些都是刀片我想:
INSERT INTO Questions (HistID, Question, AnswerID)
VALUES (
2,
'A major cause of the growth of state and Federal highway systems after World War II was the ___',
'C'
)
Declare @QuestionID INT = SCOPE_IDENTITY()
INSERT INTO Answers(QuestionID, AnswerID, Choice)
VALUES
(
@QuestionID,
'A',
'increased use of mass transit systems'
),
(
@QuestionID,
'B',
'growing prosperity of inner-city areas'
),
(
@QuestionID,
'C',
'rapid development of suburbs'
),
(
@QuestionID,
'D',
'return of city dwellers to farm areas'
)
預期輸出: 我想上面的命令(或者它應該改變成什麼)來對這些表進行以下更改:
Questions:
QuestionID HistID Question AnswerID
--------------------------------------------------------
1 2 "A major cause of the... C
Answers:
QuestionID AnswerID Choice
--------------------------------
1 A increased use of mass transit systems
1 B growing prosperity of inner-city areas
1 C rapid development of suburbs
1 D return of city dwellers to farm areas
這是SQL Server嗎? – tadman
Microsoft SQL Server,是的 –
而不是(選擇計數())你應該使用@@ IDENTITY或SCOPE_IDENTITY() – JamieD77