SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
Register Now and get your question answered!
Save Password
Forgot your Password?

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 Update if exist or insert the new record
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Yak Posting Veteran

86 Posts

Posted - 11/01/2013 :  05:45:08  Show Profile  Reply with Quote
I have this table:

CREATE TABLE [dbo].[Location](
[LocationID] [int] IDENTITY(1,1) NOT NULL,
[Location] [nvarchar](255) NOT NULL,
[Product_Code] [nvarchar](255) NOT NULL UNIQUE,
[LocationProductStockAmt] decimal(18,2),
CONSTRAINT fk_Location_ProductCode FOREIGN KEY (Product_Code) REFERENCES Product(Product_Code),

I created this dummy data:

INSERT INTO LOCATION VALUES ('Johannesburg', '1231', 4000)
INSERT INTO LOCATION VALUES ('Pretoria', '1232', 7236)
INSERT INTO LOCATION VALUES ('East London', '1233', 1256)
INSERT INTO LOCATION VALUES ('Cape Town', '1234', 1258)
INSERT INTO LOCATION VALUES ('Bloemfontein', '1235', 1458)
INSERT INTO LOCATION VALUES ('Rustenburg', '1236', 2145)
INSERT INTO LOCATION VALUES ('Cape Town', '1237', 1236)
INSERT INTO LOCATION VALUES ('Polokwane', '12310',1256)
INSERT INTO LOCATION VALUES ('Kimberly', '1238', 1256)
INSERT INTO LOCATION VALUES ('Welkom', '1239', 1235)

Now I need to create a database object that When a record or records are added or altered by whatever means to Location and the record exists already, based on the "Code" field then the record should be updated with a suffix of " - Updated", if the record does not exist insert the new record

Help please.

Flowing Fount of Yak Knowledge

4614 Posts

Posted - 11/01/2013 :  12:03:41  Show Profile  Reply with Quote
What version of SQL server are you using?

If 2008+ then I'd suggest you use a merge statement. Other wise you can "upsert" (combination of update and insert).

here is a link that may help:

EDIT: Too early in the morning, I thought I was still in the "New to SQL Server" forum. So, yeah, I'd suggest a Merge statement. :)

Edited by - Lamprey on 11/01/2013 12:07:28
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.06 seconds. Powered By: Snitz Forums 2000