|
-
Aug 8th, 2002, 08:20 AM
#1
Thread Starter
Lively Member
Bit of advice with my Triggers
Hiya
I've created a Trigger on a Customers Table within my SQL Server 2k db that checks for an Entry with the same name. If one si found thenit rolls back the transaction to my app
Alter TRIGGER chk_for_duplicate_cust ON [dbo].[tbl_cust]
FOR INSERT
AS
DECLARE @name varchar(100), @count int
SELECT @name = i.CustomerName
FROM Inserted i
SELECT @count = COUNT(c.[CustomerName])
FROM tbl_cust c
WHERE c.CustomerName = @name
IF (@count > 1)
BEGIN
RAISERROR ('The Customer %s already Exists, 16, 1, @name)
ROLLBACK TRAN
END
This works fine but it is pretty hacked together (i.,e. the count has to be >1)
Is there a better way of writing the Trigger SQL perhaps using the EXISTS statement?
Any ideas would be great
cheers
Tom
-
Aug 8th, 2002, 08:50 AM
#2
Fanatic Member
You could use EXISTS like this...
IF EXISTS (SELECT *FROM Inserted i, tbl_cust c
WHERE c.CustomerName = i.CustomerName)
BEGIN
RAISERROR ('The Customer %s already Exists, 16, 1, @name)
ROLLBACK TRAN
END
-
Aug 8th, 2002, 09:38 AM
#3
Thread Starter
Lively Member
That seems to make sense but.....
everytime i try to add a customer now it rolls back the transaction!
I've altered my Trigger so it now reads:
Alter TRIGGER chk_for_duplicate_cust ON [dbo].[tbl_cust]
FOR INSERT
AS
IF EXISTS (SELECT * FROM Inserted i, tbl_cust c
WHERE c.CustomerName = i.CustomerName)
BEGIN
RAISERROR ('The Customer already Exists', 16, 1)
ROLLBACK TRAN
END
Sorry to ask for help again but i'm stumped! I tried using a Trigger along the same lines to begin with and couldn't get it to work. No doubt ive made a stoopid mistake somewhere. Any Ideas?
Cheers
t
-
Aug 8th, 2002, 09:44 AM
#4
Fanatic Member
Do you have an Id on your table you could check?
Code:
IF EXISTS (SELECT * FROM Inserted i, tbl_cust c
WHERE c.Id <> i.Id AND c.CustomerName = i.CustomerName)
BEGIN
RAISERROR ('The Customer already Exists', 16, 1)
ROLLBACK TRAN
END
-
Aug 8th, 2002, 09:48 AM
#5
Thread Starter
Lively Member
mate you are an absolute legend!
That works a treat kid!
Thanks for the help it was legendary!
By the way your rabbit piture is quality!
Nice 1
tom
-
Aug 8th, 2002, 09:49 AM
#6
Fanatic Member
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|