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 |
stahorse
Yak Posting Veteran
86 Posts |
Posted - 2013-11-01 : 05:45:08
|
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 pk_Location_ID PRIMARY KEY (LocationID), CONSTRAINT fk_Location_ProductCode FOREIGN KEY (Product_Code) REFERENCES Product(Product_Code),) ON [PRIMARY]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 recordHelp please. |
|
Lamprey
Master Smack Fu Yak Hacker
4614 Posts |
Posted - 2013-11-01 : 12:03:41
|
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:http://www.sergeyv.com/blog/archive/2010/09/10/sql-server-upsert-equivalent.aspxEDIT: 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. :) |
|
|
|
|
|
|
|