Can someone plz Query this..

Mansoor Mohammed 61 Reputation points
2021-07-22T20:01:29.517+00:00

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

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,822 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,639 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Erland Sommarskog 111.5K Reputation points MVP
    2021-07-22T21:18:05.237+00:00

    For this type of question it is a great idea to post CREATE TABLE statements for your tables and INSERT statements for your test data. Finally it helps to have the expected result given the test data. This makes it easy to copy and paste into a query window to develop a tested solution.

    Since you did not do this, you will get an untested solution which is based on a guess of what you want.

    SELECT t1.OrderNumber, t1.item, coalesce(t1.Date, t2.Date)
    FROM   table1 t1
    LEFT  JOIN table t2 ON t1.OrderNumber = t2.OrderNumber
    
    0 comments No comments

  2. MelissaMa-MSFT 24,196 Reputation points
    2021-07-23T01:42:31.353+00:00

    Hi @Mansoor Mohammed ,

    Welcome to Microsoft Q&A!

    Please also refer below:

    insert into table3  
    select a.OrderNumber,a.Item,isnull(a.Date,b.Date)   
    from table1 a  
    inner join table2 b on a.OrderNumber=b.OrderNumber  
    

    OR

    insert into table3  
    select * from table1  
    where date is not null  
    union  
    select b.* from table1 a  
    inner join table2 b on a.OrderNumber=b.OrderNumber  
    where a.Date is null  
    

    Best regards,
    Melissa


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.