Link to home
Start Free TrialLog in
Avatar of dsulkar
dsulkar

asked on

Splitting Columns and creating new records.

Customer has entered in some contacts together “Sara and Jack Smith” BUT
They want them as separate contacts  “Sara Smith” and “Jack Smith”
The only problem is that it takes pieces of peoples names like brANDon or companies like James & james LLC.
Alos, I am getting three records instead of two from the following script.  What am I doing wrong?  
Thanks in advance!
SELECT  FirstName, * FROM  ContactName WHERE  FirstName LIKE '%&%'   

BEGIN TRAN
SELECT cn.* 
INTO #tempcontact 
FROM contactname cn 
	JOIN entity e ON cn.uniqentity = e.uniqentity
					and e.entkey = 'CUST'
WHERE firstname like '%&%'
	AND rtrim(firstname) NOT LIKE '%&'

INSERT INTO contactname (UniqFixedContactName, UniqEntity, FirstName, LastName, UniqContactAddressMain, UniqContactNumberMain, InsertedByCode)
SELECT 
UniqFixedContactName = -1,
UniqEntity,
firstname = ltrim(replace(substring(firstname, charindex('&',firstname,1),30),'&','')),
LastName,
UniqContactAddressMain,
UniqContactNumberMain,
InsertedByCode = 'BBB'
FROM  #tempcontact

UPDATE contactname
SET UniqFixedContactName = UniqContactName
WHERE UniqFixedContactName = -1
AND InsertedByCode = 'BBB'

UPDATE cn
SET  FirstName = substring(FirstName, 1, charindex('&',firstname,1) - 1), UpdatedByCode = 'BBB', UpdatedDate = GETUTCDATE()
FROM contactname cn
where uniqcontactname in (select uniqcontactname from #tempcontact)

SELECT * FROM contactname WHERE  UpdatedByCode = 'BBB' OR InsertedbyCode = 'BBB'
ORDER BY uniqentity

DROP TABLE #tempcontact

ROLLBACK

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of David Johnson, CD
David Johnson, CD
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
use " and " as the separator -- include the space characters at the front and back of the "and" literal.