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
 General SQL Server Forums
 New to SQL Server Programming
 how to insert or update from one table to another

Author  Topic 

mohan123
Constraint Violating Yak Guru

252 Posts

Posted - 2012-12-13 : 06:16:54
Hello all

i have 2 cases in which i am facing some issues.How to delete records when from one table A and Table B

for scenario :
Case 1 :
table A have 100 records and Table B have 200 records

now i need to insert data of table A into table B so in need to delete as well as insert how it can be possible???
Case 2 :
in another case i need to insert and update

insert into Speciality(SpecialityName,Description,SpecialityCode,CreatedByUserId)
select SpecialityName,Description,SpecialityCode,21
from Speciality1 where exists (select 1 from Speciality)

but this query is not working???

P.V.P.MOhan

bandi
Master Smack Fu Yak Hacker

2242 Posts

Posted - 2012-12-13 : 06:34:11
I am not clear about your requirement...
If you want to do either insert or delete/Update based on some condition, go ahead with MERGE

--
Chandu
Go to Top of Page

mohan123
Constraint Violating Yak Guru

252 Posts

Posted - 2012-12-13 : 07:16:33
i have 100 records in table A and 200 rcords in table B.Here i need to upate 100 records in table B and delete rest of records in table B

P.V.P.MOhan
Go to Top of Page

bandi
Master Smack Fu Yak Hacker

2242 Posts

Posted - 2012-12-13 : 07:22:26
Use MERGE statement..

MERGE TableB as b
USING TableA as a
ON yourCondition
WHEN MATCHED THEN
UPDATE SET b.col1 = a.col1, b.col2 = a.col2 ............
WHEN NOT MATCHED THEN
DELETE;

http://www.databasejournal.com/features/mssql/article.php/3759636/SQL-Server-2008-MERGE-Statement.htm


--
Chandu
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-12-14 : 02:25:10
quote:
Originally posted by bandi

Use MERGE statement..

MERGE TableB as b
USING TableA as a
ON yourCondition
WHEN MATCHED THEN
UPDATE SET b.col1 = a.col1, b.col2 = a.col2 ............
WHEN NOT MATCHED BY SOURCE THEN
DELETE;

http://www.databasejournal.com/features/mssql/article.php/3759636/SQL-Server-2008-MERGE-Statement.htm


--
Chandu



------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -