Join table on specific condition SQL

I have table A and B.

I want to basically join Table B to table A only if it meets certain conditions (otherwise display NULL). Table A has the transaction recorded and Table B has the actual username that recorded that transaction if it was an external user.

Unfortunately, my idea on how to make this possible either 1) exclude results where it was made by an internal user 2) throw a conversion failed error because internal users don’t exist in Table B AND are in a different format for that column being joined.

The joined column (application name) has Internal users with ‘Microsoft SQL Server Management Studio – Query’ but external users have ‘674d9234206-3p57-3453-8935-8641dufwhaih20f9’ which Table B has.

This query gives me the conversion error:

select TableB.userid,TableA.*
left outer join TableB on cast(TableB.TransactionId as varchar(36)) = TableA.ApplicationName

This query excludes my internal user from the results:

select TableB.userid,TableA.*
join TableB on cast(TableB.TransactionId as varchar(36)) = TableA.ApplicationName

I would want the userid column to display from Table B if it was an external user, otherwise default to NULL or the column indicating INTERNAL_USER. Is this even possible? I think I read something about coalesce but I don’t know how to use it when the join isn’t even possible.

Related Posts