SQL Server如果存在则更新else插入

时间:2017-02-24 07:41:04

标签: sql-server

以下查询不检查更新语句总是只插入,我在下面的代码中做错了。

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

尝试从localdb更新数据到remoteserver。

1 个答案:

答案 0 :(得分:2)

你的proc的最后一行

WHERE JT.REPAIRNO=SJ.REPAIRNO

不选择任何特定的工号。它只是从源中选择一个随机记录并插入它。

将其更改为:

WHERE JT.REPAIRNO=@JobOrder