Trying to insert only unique items into one table and then create a many to many relationship in a join table only if that join does not exist
You could use NOT EXISTS as your first insert (or LEFT JOIN / IS NULL) for the second insert to work like the first, insert only when the row doesn't exist. Another way is with EXCEPT:

INSERT INTO B (Name) 
SELECT firstname FROM @temptable
EXCEPT 
SELECT Name FROM B ;


INSERT INTO AtoB (AId, BId) 
SELECT @tableAid, B.Id FROM B JOIN @temptable T ON B.Name = T.firstname 
EXCEPT
SELECT Aid, Bid FROM AtoB ;