The below query not checking update statement always insert only , where i am doing the wrong in the below code.
ALTER Procedure [dbo].[UpdateData]
@JobOrder varchar(50)
AS
BEGIN
--DECLARE @UPDATING INT
IF EXISTS(SELECT 1 FROM [ADDLINKSERVER].[DATABASE].[dbo].[TABLE] WHERE JobOrder=@JobOrder ORDER BY JobStatus DESC)
BEGIN
UPDATE [ADDLINKSERVER].[DATABASE].[dbo].[TABLE]
SET
RepairComment = (SELECT Top 1 Status_Comment FROM LOCALDB.dbo.LOCALTABLE Where REPAIRNO=@JobOrder Order By TRACKINGID desc),
Amount = (SELECT Top 1 LABOR_AMT+PARTS_AMT As Amount FROM LOCALDB.dbo.LOCALTABLE Where REPAIRNO=@JobOrder Order By TRACKINGID desc),
JobStatus = (SELECT Top 1 Job_Status FROM LOCALDB.dbo.LOCALTABLE Where REPAIRNO=@JobOrder Order By TRACKINGID desc)
WHERE JobOrder=@JobOrder
END
ELSE BEGIN
INSERT INTO [ADDLINKSERVER].[DATABASE].[dbo].[TABLE](JobOrder,RepairComment,JobStatus,Branch,Customer,
Contact,Technician,ReceiptDate,Complaint,Amount,Warranty,ServiceType)
(
Select Top 1
JT.REPAIRNO,JT.StatusComment,JT.JobStatus,
SJ.MAINSC,SJ.CUSTOMER + ' ' + SJ.CUSTOMERLAST AS FullName,SJ.Tel,SJ.ENGINEER,SJ.RECEIPTDATE,
SJ.DEFECTDESC,SJ.LABOR_AMT+PARTS_AMT As Amount,SJ.WARRANTY,SJ.SERVICETYPE
FROM
LOCALDB1 SJ
INNER JOIN LOCALDB2 JT ON
JT.REPAIRNO=SJ.REPAIRNO
WHERE JT.REPAIRNO=SJ.REPAIRNO)
END
END
trying to update the data to remoteserver from localdb.
The last line of your proc
WHERE JT.REPAIRNO=SJ.REPAIRNO
Does not select any particular job number. It just picks a random record from the source and inserts it.
Change it to this:
WHERE JT.REPAIRNO=@JobOrder
To debug this simply put in a valid @JobOrder value and execute the code Highlighting from the "SELECT *" after the second dash commenting out the line......execute the sql and make sure the results are correct
BEGIN
UPDATE [ADDLINKSERVER].[DATABASE].[dbo].[TABLE]
SET
RepairComment = lc.Status_Comment,
Amount = lc.Amount,
JobStatus = lc.Job_Status
--SELECT *
FROM [ADDLINKSERVER].[DATABASE].[dbo].[TABLE] as t1
INNER JOIN (SELECT top 1 Status_Comment
,LABOR_AMT+PARTS_AMT As Amount
,Job_Status
FROM LOCALDB.dbo.LOCALTABLE
Where REPAIRNO=@JobOrder
Order By TRACKINGID desc) as lc
ON t1.JobOrder=lc.REPAIRNO
WHERE t1.JobOrder=@JobOrder
Rather than going this way you get count of your result and check if count >0 than update else you can insert
SELECT COUNT(*)
INTO l_cnt
FROM table
IF( l_cnt > 0 )
THEN
Update
END IF;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.