I am working on SQL Server 2008R2
, I am having the following Table
ID Name date
1 XYZ 2010
2 ABC 2011
3 VBL 2010
Now i want to prevent insertion if i have a Data although the ID is different but data is present
ID Name date
4 ABC 2011
Kindly guide me how should i write this trigger.
You can use a PRIMARY KEY or a UNIQUE Index on a table with the appropriate fields to stop duplicate records. Let us take an example – The following table contains no such index or primary key, so it would allow duplicate records for first_name and last_name.
The SQL DISTINCT keyword, which we have already discussed is used in conjunction with the SELECT statement to eliminate all the duplicate records and by fetching only the unique records.
Something like this:
CREATE TRIGGER MyTrigger ON dbo.MyTable
AFTER INSERT
AS
if exists ( select * from table t
inner join inserted i on i.name=t.name and i.date=t.date and i.id <> t.id)
begin
rollback
RAISERROR ('Duplicate Data', 16, 1);
end
go
That's just for insert, you might want to consider updates too.
Update
A simpler way would be to just create a unique constraint on the table, this will also enforce it for updates too and remove the need for a trigger. Just do:
ALTER TABLE [dbo].[TableName]
ADD CONSTRAINT [UQ_ID_Name_Date] UNIQUE NONCLUSTERED
(
[Name], [Date]
)
and then you'll be in business.
If you are using a store procedure inserting data into the table, you don't really need a trigger. You first check if the combination exists then don't insert.
CREATE PROCEDURE usp_InsertData
@Name varchar(50),
@Date DateTime
AS
BEGIN
IF (SELECT COUNT(*) FROM tblData WHERE Name = @Name AND Date=@Date) = 0
BEGIN
INSERT INTO tblData
( Name, Date)
VALUES (@Name, @Date)
Print 'Data now added.'
END
ELSE
BEGIN
Print 'Dah! already exists';
END
END
The below trigger can used if you are not inserting data via the store procedure.
CREATE TRIGGER checkDuplicate ON tblData
AFTER INSERT
AS
IF EXISTS ( SELECT * FROM tblData A
INNER JOIN inserted B ON B.name=A.name and A.Date=B.Date)
BEGIN
RAISERROR ('Dah! already exists', 16, 1);
END
GO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With