You will need to convert the binary(16) to a string. A sample of how to do this can be found in the question below. This question converts a varbinary to a string, but the same technique can be used for a binary column or variable:
SQL Server converting varbinary to string
Example code for how to do this is below:
declare @bin binary(16), @str varchar(50)
set @bin = 0x0007914BFFEC4603A6900045492EFA1A
set @str = '0007914BFFEC4603A6900045492EFA1A'
select @bin as'binary(16)', @str as 'varchar(50)'
-- the binary value is not equal to the string value
-- this statement returns 'binary value is not equal to string'
if @bin = @str select 'binary value is equal to string'
else select 'binary value is not equal to string'
declare @binstr varchar(50)
select @binstr = convert(varchar(50), @bin, 2)
select @binstr
-- the converted string value matches the other string
-- the result of this statement is "converted string is equal"
if @binstr = @str select 'converted string is equal'
else select 'converted string is NOT equal'
To use this in a join, you can include the conversion in the ON
clause of the inner join or in a WHERE
clause:
select *
from TableA
inner join TableB
on TableB.char_fk = convert(varchar(50), TableA.bin_pk, 2)
UPDATE
For SQL Server 2005, you can use an XML approach shown by Peter Larsson here:
-- Prepare value
DECLARE @bin VARBINARY(MAX)
SET @bin = 0x5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8
-- Display the results
SELECT @bin AS OriginalValue,
CAST('' AS XML).value('xs:hexBinary(sql:variable("@bin"))', 'VARCHAR(MAX)') AS ConvertedString
You can also use the undocumented function sys.fn_varbintohexstr
, but as this post on dba.stackexchange.com explains, there are several reasons why you should avoid it.