3

我在我的物理 C# 代码中有一个 try catch,它只是在发生错误时跳过此插入过程并继续循环以填充数据库。然而,这是不好的编码习惯。

所以我想在IF下面的存储过程中添加一个语句,如果主键已经存在,它将跳过。我的主键是@id.

我该怎么办?

CREATE PROCEDURE InsertProc
    (
    @id int, 
    @to nvarchar(100), 
    @from nvarchar(100), 
    @subject nvarchar(100), 
    @date datetime
    )
AS
    INSERT INTO Emails_Log (Email_ID, e_To, e_From, e_Subject, e_Date) 
    VALUES (@id, @to, @from, @subject, @date)
4

4 回答 4

4
CREATE PROCEDURE InsertProc
    (
    @id int, 
    @to nvarchar(100), 
    @from nvarchar(100), 
    @subject nvarchar(100), 
    @date datetime
    )
    AS
    IF NOT EXISTS (SELECT NULL FROM Emails_Log
                    WHERE Email_ID = @ID)
    BEGIN
        INSERT INTO Emails_Log (Email_ID, e_To, e_From, e_Subject, e_Date) 
            VALUES (@id, @to, @from, @subject, @date)
    END

如果你真的想更新记录,如果已经存在,如果不存在,则插入,模式如下:

CREATE PROCEDURE InsertProc
    (
       @id int, 
       @to nvarchar(100), 
       @from nvarchar(100), 
       @subject nvarchar(100), 
       @date datetime
    )
    AS
       UPDATE Emails_Log
          SET e_To = @to, 
              e_From = @from, 
              e_Subject = @subject, 
              e_Date = @date
        WHERE Email_ID = @ID
       -- If there was no update it means that @ID does not exist,
       -- So we proceede with insert
       IF @@ROWCOUNT = 0
       BEGIN
          INSERT INTO Emails_Log (Email_ID, e_To, e_From, e_Subject, e_Date) 
               VALUES (@id, @to, @from, @subject, @date)
       END
于 2012-05-09T09:14:03.883 回答
1
CREATE PROCEDURE InsertProc
    (
    @id int, 
    @to nvarchar(100), 
    @from nvarchar(100), 
    @subject nvarchar(100), 
    @date datetime
    )
    AS
    IF EXISTS(SELECT * From Emails_Log Where Email_ID = @id)
    UPDATE Emails_Log (Email_ID, e_To, e_From, e_Subject, e_Date) 
            SET e_To = @to, e_From = @from, e_Subject = @subject, e_Date = @date
            WHERE Email_ID = @id
    ELSE
    INSERT INTO Emails_Log (Email_ID, e_To, e_From, e_Subject, e_Date) 
            VALUES (@id, @to, @from, @subject, @date)

另一种方法是使用MERGE命令。

查看SO 上的这个线程以了解更多信息

于 2012-05-09T09:15:55.987 回答
1

您可以检查表中是否存在记录并在一条语句中插入记录。

在此处输入图像描述

于 2012-05-09T09:58:13.717 回答
0

试试这个代码

CREATE PROCEDURE InsertProc
(
@id int, 
@to nvarchar(100), 
@from nvarchar(100), 
@subject nvarchar(100), 
@date datetime
)
AS
IF NOT EXISTS (SELECT Email_ID From Emails_Log Where Email_ID = @id)
BEGIN
    INSERT INTO Emails_Log (Email_ID, e_To, e_From, e_Subject, e_Date) 
        VALUES (@id, @to, @from, @subject, @date)
END
于 2012-05-09T09:28:08.147 回答