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 2008 Forums
 Transact-SQL (2008)
 T-SQL Query

Author  Topic 

Shadab Shah
Starting Member

23 Posts

Posted - 2012-07-31 : 01:03:43
Suppose i have 2 table as Emp and Emp2.

select empid from Emp where deptid=2

The output of the above query is
empid
1
2
3
5
7
9
10
16
17

Now,Insert all the above records in Emp2 from Emp where deptid=2

which should look something like this

update Emp2 set empid= empid from Emp where deptid=2

So my question is : What would be the exact query for achieving the above

lionofdezert
Aged Yak Warrior

885 Posts

Posted - 2012-07-31 : 01:25:05
INSERT INTO emp2 (empid)
select empid from Emp where deptid=2


--------------------------
http://connectsql.blogspot.com/
Go to Top of Page

Shadab Shah
Starting Member

23 Posts

Posted - 2012-07-31 : 01:37:49
Insert would not work in my case. Because there may be possibility that data may be present in Emp2 table.Hence i would like to carry on with update.Any new answer please.
Go to Top of Page

lionofdezert
Aged Yak Warrior

885 Posts

Posted - 2012-07-31 : 01:47:25
INSERT INTO emp2 (empid)
select empid from Emp
where deptid=2
AND NOT EXISTS (SELECT 1 FROM emp2 WHERE empid = emp.empid)

How can you update a record which never exists on emp2?

--------------------------
http://connectsql.blogspot.com/
Go to Top of Page

Shadab Shah
Starting Member

23 Posts

Posted - 2012-07-31 : 03:14:36
I tried your query but it is not working for me. This query does not overwrite the existing value in emp2 but it adds additional records. I want something which would overwrite the records.
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2012-07-31 : 03:55:37
[code]MERGE dbo.Emp2 AS tgt
USING dbo.Emp AS src ON src.EmpID = tgt.EmpID
WHEN NOT MATCHED BY TARGET
THEN INSERT (
EmpID
)
VALUES (
src.EmpID
)
WHEN MATCHED
THEN UPDATE
SET tgt.Col1 = src.Col1;[/code]


N 56°04'39.26"
E 12°55'05.63"
Go to Top of Page
   

- Advertisement -