CREATE TABLE [dbo].[FINAL_HS](
[EXTRACT_KEY_ID] [int] NOT NULL,
[PROJ_ID] varchar NOT NULL,
[FY_CD] varchar NOT NULL,
[PD_NO] [smallint] NOT NULL,
[SUB_PD_NO] [smallint] NOT NULL,
[BILLED_AMT] [decimal](17, 2) NOT NULL,
CONSTRAINT [PK_FINAL_HS] PRIMARY KEY CLUSTERED
(
[PROJ_ID] ASC,
[FY_CD] ASC,
[PD_NO] ASC,
[SUB_PD_NO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
INSERT INTO EXTRACT_HS (PROJ_ID, FY_CD, PD_NO, SUB_PD_NO, BILLED_AMT)
SELECT '103503.0.001','2018','4','1',100.00
INSERT INTO EXTRACT_HS (PROJ_ID, FY_CD, PD_NO, SUB_PD_NO, BILLED_AMT)
SELECT '103503.0.001','2018','4','1',50.00
SELECT * FROM EXTRACT_HS
UPDATE FINAL_HS
SET BILLED_AMT += A.BILLED_AMT
FROM EXTRACT_HS A
INNER JOIN FINAL_HS B ON A.PROJ_ID = B.PROJ_ID AND A.FY_CD = B.FY_CD AND A.PD_NO = B.PD_NO AND A.SUB_PD_NO = B.SUB_PD_NO
IF (@@ROWCOUNT = 0 )
BEGIN
INSERT INTO FINAL_HS (EXTRACT_KEY_ID, PROJ_ID, FY_CD, PD_NO, SUB_PD_NO, BILLED_AMT)
SELECT EXTRACT_KEY_ID, PROJ_ID, FY_CD, PD_NO, SUB_PD_NO, BILLED_AMT FROM EXTRACT_HS
WHERE NOT EXISTS (SELECT * FROM FINAL_HS A WHERE A.PROJ_ID = PROJ_ID AND A.FY_CD = FY_CD AND A.PD_NO = PD_NO AND A.SUB_PD_NO = SUB_PD_NO)
END
I want to insert the first record, but it it already exist update it. There is not data into the FINAL_HS table so the INSERT where not exist is not working as there is no data. When i run it, it tells me that there is a primary key violation.
How do i write this so it will update if record exist or insert.
I am trying to avoid a loop program as there are millions of rows.
Should have one row in FINAL_HS with 150 dollars as the billed_amt