• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 116
  • Last Modified:

SQL Query- Check if exist then insert

I am using SQL Server and I have a table names Campaign that contains (AccountID, campaign, date, cost, impressions, clicks) and I would like to write a query that check through the table records if they found date=@Date then update the record if didn't find the date then insert as new record.

any help
Thank you
0
Rawan Jambi
Asked:
Rawan Jambi
  • 2
1 Solution
 
Vikas GargBusiness Intelligence DeveloperCommented:
HI,

You can try this

Update Campaign
set column = value
where date = @date

INSERT INTO COMPAIGN

SELECT * FROM TABLE WHERE DATE NOT IN (SELECT DATE FROM CAMPAIGN)
AND DATE = @DATE
0
 
Vitor MontalvãoMSSQL Senior EngineerCommented:
Vikas gave a good solution but he's assuming that the data are coming from a table. Is that correct?
If so and if the table have plenty of records, than you may want to execute the update and insert in a transaction so it's be protected against any data change during the process.

Cheers
0
 
Vikas GargBusiness Intelligence DeveloperCommented:
@Vitor,

It is not clear from the post that from where the data will come and the above was a method by using which the Asker can achieve his goal
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now