简体   繁体   中英

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 . For example,

I have a table called 'STU' with the following columns:

  • SNO (Primary Key, and Identity [ie autoincrementing])
  • NAME (not null)
  • CLASS (not null)
  • SECTION (not null)

I have a table called 'MARK' with the following columns:

  • MSNO (Foreign Key reference STU (SNO))
  • M1 (not null)
  • M2 (not null)
  • M3 (not null)

     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.

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. It needs to be a valid SELECT statement. Appending VALUES won't achieve that.

If you need to visualise what you're going to insert before you insert it, simply run the SELECT query first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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