views:

237

answers:

3

Hi,

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  A: 

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"?

gbn
this is not safe for concurrency, with heavy concurrency you will get dupes.
Sam Saffron
Always worth adding the unique key constraint too and using an appropriate locking level.
pjp
@Sam: True, seen it happen, but it's OK for a lot of situations. @pjp: The PK would normally be the unique constraint
gbn
+1  A: 

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.

no_one
I am using SQL Server 2005.
MKS
Thanks Dear! for your help
MKS
+2  A: 

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
pjp