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)
 Insert from T2 into @TempTable if there is no row

Author  Topic 

e.bar
Starting Member

25 Posts

Posted - 2008-05-15 : 14:38:52
How insert values from TABLE2 into @TempTable if a row into TABLE1 not in TABLE2?

--Query:
DECLARE @TempTable (IdTemp int, TempDate datetime)
INSERT INTO @TempTable (IdTemp, TempDate)
SELECT T1.Id, MAX(T2.Date2)
FROM Table1 T1 INNER JOIN Table2 T2 ON T1.Id = T2.Id
GROUP BY T1.Id

/*
Example:
TABLE1 Id = '1'
TABLE2 = Id '1' not exists
*/

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-05-15 : 14:40:50
[code]DECLARE @TempTable (IdTemp int, TempDate datetime)
INSERT INTO @TempTable (IdTemp, TempDate)
SELECT ISNULL(T1.Id,T2.Id), MAX(T2.Date2)
FROM Table1 T1
RIGHT JOIN Table2 T2 ON T1.Id = T2.Id
GROUP BY ISNULL(T1.Id,T2.Id)[/code]
Go to Top of Page

e.bar
Starting Member

25 Posts

Posted - 2008-05-15 : 15:27:33
Hmmm, it does not work. I received code below that worked fine.
Tks.

--Query:
DECLARE @TempTable (IdTemp int, TempDate datetime)
INSERT INTO @TempTable (IdTemp, TempDate)
SELECT T1.Id, MAX(T2.Date2)
FROM Table1 T1
Left JOIN Table2 T2
ON T1.Id = T2.Id
GROUP BY T1.Id
Go to Top of Page
   

- Advertisement -