Click here to Skip to main content
15,914,109 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi i have two table in sql server 2008 i want to get last record from table 1 ,i know this,
but after that, i want to compare this field with another table that have same field
i mean this:
table 1:
time
19:09:08
table 2
time:
19:09:00
19:08:00
i want to get that 19:09 that Exist in table1, is in table 2 or not؟ if yes i want to update if no i want to insert but i do not know how i can do this in query?
please help me
thanks a lot
Posted
Updated 27-May-12 21:40pm
v2
Comments
Maciej Los 28-May-12 5:36am    
Please, be more specific... Are both tables related each other? What Primary Key and Foreign Key?
farid_12 28-May-12 6:23am    
yes they related with each other id that is pk in two table
Maciej Los 30-May-12 17:17pm    
This information is not complete. How can we help you, if we don't know the structure of database, the relations between tables and so on? Show an example using the names of columns and dependencies between them.
RDBurmon 8-Jun-12 8:26am    
Thanks Everyone who replied to this thread , So Farid, I think you have got enough response and you should be able to mark it as your answer and close the thread.

could be something like this?

SQL
DECLARE @time1 as datetime;

SELECT TOP 1 @time1 = time FROM table1 ORDER BY ID DESC;

IF ((SELECT COUNT(*) FROM table2 WHERE time = @time1) = 0)
BEGIN
	INSERT INTO table2 VALUES (@time1);
END
ELSE
BEGIN
  UPDATE table2 SET time = time1 WHERE time = @time1;
END


supousing ID is the pk of table1 and is identity that help us to know the last record
 
Share this answer
 
you can use
SQL
SUBSTRING('19:09:00',1,5)
in both the table column
 
Share this answer
 
v2
Hi Farid,


try this code block. It works fine if you are using Sqlserver 2008

SQL
MERGE Table2 USING Table1
ON LEFT(Table2.Time,LEN(Table2.[Time])-3) = LEFT(Table1.[Time],LEN(Table1.[Time])-3)
WHEN MATCHED THEN UPDATE SET Table2.[Time] = Table1.[Time]
WHEN NOT MATCHED THEN INSERT([Time])
VALUES(Table1.[Time])
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900