Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 How to insert missing records into another table?

Author  Topic 

pras2007
Posting Yak Master

216 Posts

Posted - 2009-10-13 : 01:39:30
Hello All,

I'm joining two tables to one another and the goal is to insert all records that has a null value for S_date field into Table_B.
The following values should be inserted into Table_B:

- S_Date(Add 1 month to S_Date field) = Prev_S_Date
- Record_ID = Prev_Record_ID
- First_Name = Prev_First_Name
- Col1(Change the sign of the Col1 field) = Prev_Col1
- Col2(Change the sign of the Col2 field) = Prev_Col2

SELECT
A.S_Date,
B.S_Date AS Prev_S_Date,
A.Record_ID,
B.Record_ID AS Prev_Record_ID,
A.First_Name,
B.First_Name AS Prev_First_Name,
A.Col1,
B.Col1 AS Prev_Col1,
A.Col2,
B.Col2 AS Prev_Col2
FROM Table_B AS A full OUTER JOIN
Table_A AS B ON A.Record_ID = B.Record_ID


CREATE TABLE [dbo].[Table_A](
[S_Date] [datetime] NULL,
[Record_ID] [int] NULL,
[First_Name] [nchar](10) NULL,
[Col1] [money] NULL,
[Col2] [money] NULL
) ON [PRIMARY]


insert into table_A Values('2009-09-30 00:00:00.000',2,'Chris',-21.00,0.00)
insert into table_A Values('2009-07-31 00:00:00.000',1,'Mike',34.00,34.00)
insert into table_A Values('2009-08-31 00:00:00.000',4,'Tony',39.00,0.00)
insert into table_A Values('2009-10-13 00:00:00.000',6,'Sara',19.00,19.00)

CREATE TABLE [dbo].[Table_B](
[S_Date] [datetime] NULL,
[Record_ID] [int] NULL,
[First_Name] [nchar](10) NULL,
[Col1] [money] NULL,
[Col2] [money] NULL
) ON [PRIMARY]

insert into table_B Values('2009-08-31 00:00:00.000',3,'Sue',92.00,0.00)
insert into table_B Values('2009-08-31 00:00:00.000',4,'Tony',39.00,0.00)

Does anyone know how to accomplish to task?

Please advice.

Thanks.
   

- Advertisement -