[英]Merge 2 tables into 1 SQL Server
This is my current table: 这是我当前的表格:
Sales Table
OrderID Customer_ID Customer_Name
1 12 Bob
2 18 Ben
3 11 Harry
OrderID
is the primary key OrderID
是主键
I have a temporary table Temp1
: 我有一个临时表Temp1
:
Order_CreateDate Order_ReturnDate
20051102 20051104
20051103 20051108
20051104 20051105
I want to change the dates YYYYMMDD
in Temp1 table
, to YYYY-MM-DD
, and move it to table, this code below does not work if I insert straight into Sales Table
as it displays error saying: 我想将Temp1 table
的日期YYYYMMDD
更改为YYYY-MM-DD
,并将其移动到表中,如果我直接插入到Sales Table
,则下面的代码不起作用,因为它显示错误:
Cannot insert the value NULL into column 'Order_ID', table 'car_rental.dbo.DataInCentralDatabase2'; 无法将值NULL插入表“ car_rental.dbo.DataInCentralDatabase2”的“ Order_ID”列中; column does not allow nulls. 列不允许为空。 INSERT fails 插入失败
However if I test it out by outputting to another temporary table, temp2
, it works. 但是,如果我通过输出到另一个临时表temp2
对其进行测试,则它可以正常工作。
INSERT INTO [dbo].[sales]([Order_CreateDate])
SELECT
CONVERT(date,Order_CreateDate,111) AS Order_CreateDate
FROM dbo.temp1
But running this code two times for temp2 table
(for the two converted columns) has the following result: 但是,对于temp2 table
(对于两个转换的列)两次运行此代码,结果如下:
Order_CreateDate Order_ReturnDate
2005-11-02
2005-11-03
2005-11-04
NULL 2005-11-04
NULL 2005-11-08
NULL 2005-11-05
I know this question is extremely confusing, but as the end result I want it to become like this: 我知道这个问题非常令人困惑,但是最终我希望它变得像这样:
OrderID Customer_ID Customer_Name Order_CreateDate Order_ReturnDate
1 12 Bob 2005-11-02 2005-11-04
2 18 Ben 2005-11-03 2005-11-08
3 11 Harry 2005-11-04 2005-11-05
Any ideas on how to tackle this? 关于如何解决这个问题的任何想法?
You need another column in Temp1 table as 您需要在Temp1表中的另一列为
OrderID Order_CreateDate Order_ReturnDate
1 20051102 20051104
2 20051103 20051108
3 20051104 20051105
Use Update query and not Insert query 使用更新查询而不是插入查询
UPDATE a set
Order_CreateDate=CONVERT(datetime,b.Order_CreateDate,111),
Order_ReturnDate=CONVERT(datetime,b.Order_ReturnDate,111)
from [dbo].[sales] a join [dbo].[Temp1] b on a.OrderID = b.OrderID
At the first, you should get an updated version of temp1 like this: 首先,您应该获得temp1的更新版本,如下所示:
select
CONVERT(date,Order_CreateDate,111) as Order_CreateDate,
CONVERT(date,Order_ReturnDate,111) as Order_ReturnDate,
OrderID
into #temp2
from temp1
then, update your main table with join on temp1, like this: 然后,使用temp1上的join更新主表,如下所示:
update s
s.Order_CreateDate = t.Order_CreateDate,
s.Order_ReturnDate = t.Order_ReturnDate
from sales s
inner join #temp2 t
on s.OrderID = t.OrderID
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.