简体   繁体   English

sql server->插入到作为主键的单个值中,并将Identity()插入另一个表的列中

[英]sql server--> Insert into a single value which is a primary key as well as Identity() into a column of another table

I wanna insert a records from a column which has a primary key and Is Identity property to another column of another table . 我想从具有主键和Is Identity属性的列中插入记录到另一个表的另一列中。 For example, 例如,

I have a table called 'STU' with the following columns: 我有一个名为“ STU”的表,其中包含以下列:

  • SNO (Primary Key, and Identity [ie autoincrementing]) SNO(主键和身份[即自动递增])
  • NAME (not null) NAME(非null)
  • CLASS (not null) CLASS(非null)
  • SECTION (not null) SECTION(不为null)

I have a table called 'MARK' with the following columns: 我有一个名为“ MARK”的表,其中包含以下列:

  • MSNO (Foreign Key reference STU (SNO)) MSNO(外键参考STU(SNO))
  • M1 (not null) M1(非null)
  • M2 (not null) M2(非null)
  • M3 (not null) M3(非空)

     CREATE TABLE STU (SNO INT CONSTRAINT PK_SNO PRIMARY KEY (SNO), NAME VARCHAR(25), CLASS VARCHAR(20), SECTION CHAR ); CREATE TABLE MARK(MSNO INT CONSTRAINT FK_MSNO FOREIGN KEY (MSNO) REFERENCES STU(SNO), M1 INT, M2 INT, M3 INT); 

As the title says I am trying to insert into 1 table selecting values from other table. 就像标题所说的那样,我试图插入1个表中,从其他表中选择值。

INSERT INTO MARK (MSNO, M1, M2, M3) SELECT SNO FROM STU WHERE SNO = '%', '100','100','100';

INSERT INTO MARK (MSNO, M1, M2, M3) SELECT SNO FROM STU WHERE SNO = '%' values ('100','100','100');

Both these insert query is throwing error 这些插入查询都抛出错误

INSERT INTO MARK (MSNO, M1, M2, M3)
SELECT SNO FROM STU WHERE SNO = '%' values ('100','100','100');

I think your intent is: 我认为您的意图是:

INSERT INTO MARK (MSNO, M1, M2, M3)
SELECT SNO, '100', '100', '100' FROM STU WHERE SNO = '%'

The SELECT statement describes the data to be inserted. SELECT语句描述要插入的数据。 It needs to be a valid SELECT statement. 它必须是有效的SELECT语句。 Appending VALUES won't achieve that. 附加VALUES不能达到目的。

If you need to visualise what you're going to insert before you insert it, simply run the SELECT query first. 如果需要在插入之前可视化要插入的内容,只需先运行SELECT查询即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM