Stop Inserting in Table if record already exists

Deadly 提交于 2019-12-23 20:01:28

问题


I have sql server procedure, please see below.

ALTER PROCEDURE [dbo].[uspInsertDelegate]
(
    @CourseID int,
    @CPUserID int,
    @StatusID int,
    @CreateUser varchar(25)

)
AS
    SET NOCOUNT OFF;
INSERT INTO tblDelegate                      
(
    CourseID, 
    CPUserID, 
    StatusID, 
    CreateUser 

)
VALUES     
(
    @CourseID,
    @CPUserID,
    @StatusID,
    @CreateUser
)

RETURN

Now I don't want to insert into table tblDelegate if the inserting courseid and cpuserid is same for that records in table tblDelegate


回答1:


Simply test first. In SQL Server 2005 you could also TRY/CATCH to ignore a duplicate error.

IF NOT EXISTS (SELECT *
        FROM tblDelegate
        WHERE CourseID = @CourseID etc)
    INSERT INTO tblDelegate                      
    (
        CourseID, 
        CPUserID, 
        StatusID, 
        CreateUser 

    )
    VALUES     
    (
        @CourseID,
        @CPUserID,
        @StatusID,
        @CreateUser
    )

May I ask: do you mean "SET NOCOUNT ON"?




回答2:


Add a unique key constraint to the courseid and cpuuserid columns.

You'll then get a key violation if you try to insert a dupe.

As well as doing this you can test to see if the value exists before inserting it using your stored procedure.

BEGIN TRAN

SELECT 1 
FROM tblDelegate WITH (TABLOCK) 
WHERE CourseId=@CourseID 
      AND CPUserID=@CPUserId
IF @@rowcount = 0
BEGIN
--Record doesn't already exist
--Insert it
END

COMMIT



回答3:


What version of SQL Server you are using ? If you are on 2008 look up the MERGE statement.

Use the IF NOT Exists Clause then as pointed in the first answer.



来源:https://stackoverflow.com/questions/1388235/stop-inserting-in-table-if-record-already-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!