【问题标题】:Insert values from one table to another having different primary key将值从一个表插入到另一个具有不同主键的表中
【发布时间】:2019-01-06 22:40:53
【问题描述】:

我有 2 张桌子。标签 A 和标签 B

标签 A

Id       Name
2        John
3        Peter
4        Rachel

我需要在表 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 是表 B 的主键,Id 来自表 A,其余值是硬编码的。

请建议脚本做同样的事情

【问题讨论】:

  • 表 1 的 ID 将被视为表 2 中的 foreign key,因此将表 1 中的键插入表 2 中的 foreign keyID 应该没有问题跨度>
  • 听起来你在问how to create a foreign key
  • PrId 是一种身份吗?

标签: sql sql-server sql-server-2008 sql-server-2008-r2


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    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

    以后请在发帖前做一些研究

    【讨论】:

    • 表 B 是一个空表。如上所示,我需要填充表 B 中的数据。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-29
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多