简体   繁体   中英

Insert values from one table to another having different primary key

I have 2 tables. Tab A and Tab B

Tab A

Id       Name
2        John
3        Peter
4        Rachel

I need to insert records in table B to get following:

Tab B

PrId    ID       Resident     Date.
1       2        Yes          7/1/2018
2       3        Yes          7/1/2018
3       4        Yes          7/1/2018

PrId is the primary key of table B, Id comes from Table A and rest of the values are hard coded.

Please suggest the script to do the same

Are you looking to simply do a straight-forward insert from one table into another? If so, here's an example you can run in SSMS:

-- create table variables for illustration purposes --

DECLARE @tableA TABLE ( [Id] INT, [Name] VARCHAR(10) );
DECLARE @tableB TABLE ( [PrId] INT IDENTITY (1, 1), [Id] INT, [Resident] VARCHAR(10), [Date] SMALLDATETIME );

-- insert sample data into @tableA --

INSERT INTO @tableA ( [Id], [Name] ) VALUES ( 2, 'John' ), ( 3, 'Peter' ), ( 4, 'Rachel' );

-- show rows in @tableA --

SELECT * FROM @tableA;

/*
    +----+--------+
    | Id |  Name  |
    +----+--------+
    |  2 | John   |
    |  3 | Peter  |
    |  4 | Rachel |
    +----+--------+
*/

-- insert records from @tableA to @tableB --

INSERT INTO @tableB (
    [Id], [Resident], [Date]
)
SELECT
    [Id], 'Yes', '07/01/2018'
FROM @tableA;

-- show inserted rows in @tableB --

SELECT * FROM @tableB;

/*
+------+----+----------+---------------------+
| PrId | Id | Resident |        Date         |
+------+----+----------+---------------------+
|    1 |  2 | Yes      | 2018-07-01 00:00:00 |
|    2 |  3 | Yes      | 2018-07-01 00:00:00 |
|    3 |  4 | Yes      | 2018-07-01 00:00:00 |
+------+----+----------+---------------------+
*/

If you have your tables set up with a Primary Key and Foreign Key then you can run the following select query to join the two tables into one.

select a.PrId, b.ID, a.Resident, a.Date 
from Table a inner join 
Table b on a.PrID = b.ID

look up inner joins here https://www.w3schools.com/sql/sql_join_inner.asp

and foreign key https://www.w3schools.com/sql/sql_foreignkey.asp

In the future please do some research before posting

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