The problem is that you run USE master in a separate batch of dynamic SQL:
set @sql = N'USE master;'
exec(@sql)
print(@sql)
But that USE statement only has effect with that EXEC. If you add
PRINT db_name()
to the above, you will see that you are in the same database as before. But the concept as such is a little scary. You running in a stored procedure in a database and then you try to restore that database. Which means that the stored procedure may no longer exist when the RESTORE completes. What actually happens then, I don't know.