将值从一个 table 插入到另一个具有不同主键的值

Insert values from one table to another having different primary key

我有 2 个 table。选项卡 A 和选项卡 B

选项卡 A

Id       Name
2        John
3        Peter
4        Rachel

我需要在 table B 中插入记录以获得以下信息:

选项卡 B

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

PrId 是 table B 的主键,Id 来自 Table A,其余值是硬编码的。

请建议执行相同操作的脚本

如果您的表设置了主键和外键,那么您可以运行以下select查询将两个表合并为一个。

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

在此处查找内部联接 https://www.w3schools.com/sql/sql_join_inner.asp

和外键 https://www.w3schools.com/sql/sql_foreignkey.asp

以后发帖前请做一些研究

您是否希望直接从一个 table 插入另一个?如果是这样,这是一个您可以在 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 |
+------+----+----------+---------------------+
*/