![]() | |
![]() |
| | Thread Tools | Display Modes |
#1
| |||
| |||
|
#2
| |||
| |||
|
|
I have the following keys in Consumption: - Plant - Material - Month - Year The above are the primary keys in the table and the following are non-key fields: - Quantity - Amount I have data stored in this table currently but many times I get feeds which are stored in the table: Consumption_staging which as the following fields: Plant Material Month Year Quantity Amount even in the staging table - plant, material, month,year are the keys. Now I want to update data from the Consumption_staging to the Consumption table on the following criteria: If for the same Key fields as in Consumption_Staging if a record is already present in Consumption table then the record in Consumption must be updated with the non-key fields else the record from Consumption_staging must be inserted into the Consumption table. Greatly appreciate if you could kindly share the SQL code for this problem I want to just do it possibly just in SQL. Thanks Karen |
#3
| |||
| |||
|
|
update Consumption set p = CS.p , ma = CS.ma , mo = CS.mo , yr = CS.yr from Consumption_staging CS inner join Consumption C ON CS.p = C.p AND CS.ma = C.ma AND CS.mo = C.mo AND CS.yr = C.yr insert into Consumption ( p , ma, mo, yr, qu, am ) Select p , ma, mo, yr, qu, am from Consumption_staging CS left outer join Consumption C ON CS.p = C.p AND CS.ma = C.ma AND CS.mo = C.mo AND CS.yr = C.yr WHERE C.p IS NULL karenmiddleol (AT) yahoo (DOT) com> wrote in message news:1129633654.148651.61570 (AT) g14g2000cwa (DOT) googlegroups.com... I have the following keys in Consumption: - Plant - Material - Month - Year The above are the primary keys in the table and the following are non-key fields: - Quantity - Amount I have data stored in this table currently but many times I get feeds which are stored in the table: Consumption_staging which as the following fields: Plant Material Month Year Quantity Amount even in the staging table - plant, material, month,year are the keys. Now I want to update data from the Consumption_staging to the Consumption table on the following criteria: If for the same Key fields as in Consumption_Staging if a record is already present in Consumption table then the record in Consumption must be updated with the non-key fields else the record from Consumption_staging must be inserted into the Consumption table. Greatly appreciate if you could kindly share the SQL code for this problem I want to just do it possibly just in SQL. Thanks Karen |
#4
| |||
| |||
|
#5
| |||
| |||
|
#6
| |||
| |||
|
|
The insert gives more errors as follows: Server: Msg 2627, Level 14, State 1, Line 1 Violation of PRIMARY KEY constraint 'PK_Consumption. Cannot insert duplicate key in object 'Consumption'. The statement has been terminated. Thanks Karen |
![]() |
| Thread Tools | |
| Display Modes | |
| |