Table Contraints

Hi
Is it possible to apply a constraint or equivalent to a table that prevents a record being inserted when the record to be inserted already exists but the values are swapped around?

For example, if a table had two columns: FirstName and SecondName having a record FirstName = ‘John’ and SecondName = ‘Smith’ – then when another record having FirstName =’ Smith’ and SecondName =’ John’ was about to be inserted SQL would reject it.

Good luck!
antonmsAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jim HornMicrosoft SQL Server Developer, Architect, and AuthorCommented:
Yep.  You can create an insert trigger to pull this off, that goes something like this:  
CREATE TRIGGER trigger_name ON your_table
FOR INSERT
AS
IF EXISTS (SELECT * FROM your_table WHERE inserted.first_name = your_table.last_name AND inserted.last_name = your_table.first_name)   
	BEGIN
	RAISERROR ('Cant insert a row where the first and last names already exist, but in opposite order.', 16, 1);
	ROLLBACK TRANSACTION;
	RETURN 
	END;
GO

Open in new window

0
Scott PletcherSenior DBACommented:
If you want to avoid a trigger, you could also create a PERSISTED column with a unique index on it.  I can give you details on that if you'd like them.
0
antonmsAuthor Commented:
If possible I would prefer not to use a trigger - more info on the persisted column option would be great thanks.
0
Scott PletcherSenior DBACommented:
ALTER TABLE dbo.tablename
ADD FirstName_SecondName AS CASE WHEN FirstName < SecondName THEN FirstName ELSE ISNULL(SecondName, '') END + CASE WHEN FirstName < SecondName THEN SecondName ELSE ISNULL(FirstName, '') END PERSISTED

ALTER TABLE dbo.tablename
ADD CONSTRAINT tablename__UQ_FirstName_SecondName UNIQUE NONCLUSTERED ( FirstName_SecondName )
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
antonmsAuthor Commented:
Thanks
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.