SQLTeam.com | Weblogs | Forums

Can u plz Query - DateIssue

Table1

OrderNumber Item Date
1 Bat 1/1/2021
2 Ball 1/2/2021
3 Wickets

Table2
OrderNumber Item Date
1 Bat 1/1/2021
2 Ball 1/2/2021
3 Wickets 1/3/2021

Table3
OrderNumber Item Date
1 Bat 1/1/2021
2 Ball 1/2/2021
3 Wickets 1/3/2021

I have two tables Table1 and Table 2, I want to insert data into Table 3 from Table 1 and Table 2

DataType of Date
Table 1 datatime
Table 2 date
Table 3 datetime

Insert into Table3(OrderNumber, Item, Date)
Select
OrderNumber,
Item,
(If Date is null in Table1
Then Select Date from Table2)
From
Table 1

It's not that hard, I assume I can join both tables on OrderNumber. When using LEFT JOIN it means that I take all the records from Table1 and add the orders from Table2 but only if the exists, else the values will be NULL. You can use different datetime and date, the field in Table3 will make it a datetime format.

Insert into Table3(OrderNumber, Item, Date)
Select
Table1.OrderNumber,
Table1.Item,
ISNULL(Table1.Date, Table2.Date) AS [FinalDate]
From
Table1
LEFT OUTER JOIN Table2
ON Table1.OrderNumber=Table2.OrderNumber;