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.
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=2The output of the above query is empid123579101617Now,Insert all the above records in Emp2 from Emp where deptid=2which should look something like thisupdate Emp2 set empid= empid from Emp where deptid=2So 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/ |
 |
|
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. |
 |
|
lionofdezert
Aged Yak Warrior
885 Posts |
Posted - 2012-07-31 : 01:47:25
|
INSERT INTO emp2 (empid)select empid from Emp where deptid=2AND 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/ |
 |
|
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. |
 |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2012-07-31 : 03:55:37
|
[code]MERGE dbo.Emp2 AS tgtUSING dbo.Emp AS src ON src.EmpID = tgt.EmpIDWHEN 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" |
 |
|
|
|
|