user1326379
user1326379

Reputation: 170

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

Upvotes: 1

Views: 5454

Answers (2)

critical_error
critical_error

Reputation: 6706

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 |
+------+----+----------+---------------------+
*/

Upvotes: 5

Sudosu0
Sudosu0

Reputation: 157

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

Upvotes: 0

Related Questions