sql server 2012

hi,
iam having two tables ...
( Eg :  sample  ) one table have 1  (loannumber ) record other table have 3  (distinct  loan number ) records .
 i need to insert  matched record need to update not matched need to insert  how to do iam attaching sample table structure.

Like that matched records need to update with out matched need to insert


 /* This table i need 3 records as like this


      Lnno                               ExeType      Status      LstUpdt
      H1CDGRN0300164            F                 N                  Null
      BDCLMTF1403310001       P                 N                  NULL
      NRCDKSH0200004            P                 N                   NULL


 */
sample-table-structure.sql
kowsika deviAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Nitin SontakkeDeveloperCommented:
You can look into MERGE statement.
Vitor MontalvãoMSSQL Senior EngineerCommented:
Since you want to UPDATE and INSERT, get rid of the IF statement (it only performs one of the operations). Replace the IF block with the following code:
UPDATE temp 
SET [Status] = 'N', LstUpdt = NULL,
    ExeType = CASE 
			WHEN b.[status] = 'I' THEN 'P' 
			ELSE 'F' 
		END
FROM temp a (nolock)
	JOIN Loln_lnCustInstlmntDaily b (nolock) ON a.Lnno = b.lnno and State_fk=42	

INSERT INTO temp (Lnno, ExeType, [Status], LstUpdt)
SELECT l.Lnno, 'P', 'N', NULL
FROM Loln_lnCustInstlmntDaily l
WHERE NOT EXISTS (SELECT 1 FROM temp a WHERE a.Lnno = l.lnno)
GROUP BY l.lnno

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Vitor MontalvãoMSSQL Senior EngineerCommented:
Solution provided.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
SQL

From novice to tech pro — start learning today.