插入两张桌子 [英] inseting into two tables

查看:74
本文介绍了插入两张桌子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试同时插入此表格

  CREATE   TABLE  [dbo]。[QuestionTable] 

[ExamID] [ nchar ]( 10 NOT NULL
[QuestionID] [< span class =code-keyword> int ] IDENTITY 1 1 NOT NULL
[ExamQuestion ] [ nvarchar ]( 150 NULL
[ExamAnswer] [ nvarchar ]( 70 NOT NULL
[StaffID ] [ nchar ]( 12 NULL
CONSTRAINT [PK_QuestionTable] PRIMARY KEY CLUSTERED





  CREATE   TABLE  [ dbo]。[OptionsTable] 

[QuestionID] [ int ] IDENTITY 1 1 NOT NULL
[OptionsA] [ nvarchar ]( 40 NOT NULL
[OptionsB] [ nvarcha r ]( 40 NOT NULL
[OptionsC] [ nvarchar ]( 40 NOT NULL
[OptionsD] [ nvarchar ] ( 40 NOT NULL
[ExamID] [ nchar ]( 10 NOT NULL





i需要有人来让我通过请.......从未尝试过这样的事情之前请

解决方案

这两个表之间没有联系 - 你当然不会希望QuestionID在每个表中都是Identity,因为这意味着SQL将保持两个indep结果数字,所以他们可能不是我的一步。可能你想要QuestionTable一个是Identity,而OptionsTable是QuestionTable ID值的外键。





然后可能你想做的是两个插入作为一个命令:

  INSERT   INTO  QuestionTable(ExamId,ExamQuestion,ExamAnswer,StaffId)
VALUES (...);
INSERT INTO OptionsTable(QuestionId,OptionsA,OptionsB,OptionsC,OptionsD,ExamID)
VALUES @@ IDENTITY ,...)


am trying to insert into this tables simultaneously

CREATE TABLE [dbo].[QuestionTable]
(
    [ExamID] [nchar](10) NOT NULL,
    [QuestionID] [int] IDENTITY(1,1) NOT NULL,
    [ExamQuestion] [nvarchar](150) NOT NULL,
    [ExamAnswer] [nvarchar](70) NOT NULL,
    [StaffID] [nchar](12) NOT NULL,
 CONSTRAINT [PK_QuestionTable] PRIMARY KEY CLUSTERED
)



CREATE TABLE [dbo].[OptionsTable]
(
    [QuestionID] [int] IDENTITY(1,1) NOT NULL,
    [OptionsA] [nvarchar](40) NOT NULL,
    [OptionsB] [nvarchar](40) NOT NULL,
    [OptionsC] [nvarchar](40) NOT NULL,
    [OptionsD] [nvarchar](40) NOT NULL,
    [ExamID] [nchar](10) NOT NULL
)



i need someone to put me through please.......have never tried something like this before please

解决方案

There is no link between the two tables - you certainly don't want the QuestionID to be Identity in each table as that means that SQL will maintain two independant numbers, so they may not me in step. Probably, you want the QuestionTable one to be an Identity, and OptionsTable to be a Foreign key to the QuestionTable ID value.


Then probably what you want to do is two inserts as a single command:

INSERT INTO QuestionTable (ExamId, ExamQuestion, ExamAnswer, StaffId) 
VALUES (...);
INSERT INTO OptionsTable (QuestionId, OptionsA, OptionsB, OptionsC, OptionsD, ExamID)
VALUES (@@IDENTITY, ...)


这篇关于插入两张桌子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆