SQL Server存储过程 - 如果存在则跳过,否则插入

时间:2018-05-16 14:58:42

标签: sql sql-server stored-procedures

我无法创建存储过程来跳过现有数据并插入不存在的数据。

以下是当前代码:

ALTER PROCEDURE [dbo].[PrezentaImport2]
    @CodAngajat INT,
    @Data DATE,
    @CodTipOra VARCHAR(50),
    @R1DAL NUMERIC(10,1),
    @R1ALL NUMERIC(10,1),
    @R1TOT NUMERIC(10,1),
    @IdUtilizatorAdaugare INT
AS
    INSERT INTO Prezente (IdAngajat, IdTipPostDeLucru, IdPostDeLucru, IdDepartament, 
                          IdEchipa, IdLinie, Data, IdTipOra, R1DAL, R1ALL, R1TOT, 
                          IdUtilizatorAdaugare, DataAdaugare)
        SELECT 
            Angajati.Id, Angajati.IdTipPostDeLucru, Angajati.IdPostDeLucru, Angajati.IdDepartament,
            Angajati.IdEchipa, Angajati.IdLinie, @Data, TipuriOre.Id, @R1DAL, @R1ALL, @R1TOT,
            @IdUtilizatorAdaugare, GETDATE()
        FROM 
            Angajati
        INNER JOIN 
            TipuriOre ON TipuriOre.CodTipOra = @CodTipOra 
                      AND Angajati.CodAngajat = @CodAngajat

谢谢。

1 个答案:

答案 0 :(得分:0)

您的代码看起来像SQL Server。典型方法使用merge。它看起来像这样:

ALTER PROCEDURE [dbo].[PrezentaImport2] (
    @CodAngajat INT,
    @Data DATE,
    @CodTipOra VARCHAR(50),
    @R1DAL NUMERIC(10,1),
    @R1ALL NUMERIC(10,1),
    @R1TOT NUMERIC(10,1),
    @IdUtilizatorAdaugare INT
AS
BEGIN
    MERGE Prezente as target
        USING (SELECT . . .
               FROM Angajati a INNER JOIN
                    TipuriOre t
                    ON t.CodTipOra = @CodTipOra AND a.CodAngajat = @CodAngajat
              )
        ON target.? - source.?
    WHEN MATCHED THEN
        UPDATE SET IdAngajat = source.IdAngajat,
                   IdTipPostDeLucru = source.IdTipPostDeLucru,
                   . . .
    WHEN NOT MATCHED THEN
        INSERT (IdAngajat, IdTipPostDeLucru, IdPostDeLucru, IdDepartament, IdEchipa, IdLinie, Data, IdTipOra, R1DAL, R1ALL, R1TOT, IdUtilizatorAdaugare, DataAdaugare)
            VALUES (source.Id, source.IdTipPostDeLucru, source.IdPostDeLucru, source.IdDepartament, source.IdEchipa, source.IdLinie, @Data, source.Id, @R1DAL, @R1ALL, @R1TOT, @IdUtilizatorAdaugare, GETDATE()
    END;
END;

您需要使用定义重复的列填充?,并使用所需的其余赋值语句填充. . .