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

时间:2018-07-30 16:05:29

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

我有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,其余值都经过硬编码。

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

2 个答案:

答案 0 :(得分:4)

您是否要简单地从一张桌子直接插入另一张桌子?如果是这样,这是您可以在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 |
+------+----+----------+---------------------+
*/

答案 1 :(得分:0)

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

>>> df = df.withColumn('dt_ts', dt_to_timestamp()(func.col('dt')))
>>> df = df.withColumn('dt_ts', func.col('dt_ts').cast(DoubleType()))
>>> df.show(5, False)
+---------------------+--------------+
|dt                   |dt_ts         |
+---------------------+--------------+
|2018-01-17 19:00:15.0|1.516237215E12|
|2018-01-17 19:00:16.0|1.516237216E12|
+---------------------+--------------+

https://www.w3schools.com/sql/sql_join_inner.asp

处查找内部联接

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

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