问题
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