There are some plugins that can do this easily. but if you wanna do it with commands, its going to be annoying.
Because you first need to track the player is holding a sword (which is a easy thing to do)
but the hard part is tracking the right click:
for tracking the right click you need to use carrot on stick on player's offhand, but if you do that when ever you right click, the carrot on stick will be replaced with shield. and if you want to track the right click with shield, its going to replace with carrot on stick instantly.
so i think its better to use plugins instead of commands.