I have a query which joins two tables based on a timestamp
value (don't ask).
One of these tables stores the data in a column with a Timestamp
data type. The other stores it as a varchar
.
Previously, the query converted the timestamp
column to a varchar
for the join. As I understand it this is not sargable, so I'd like to do the reverse. (The timestamp
table is much larger and efficiency is more of an issue).
SELECT *
FROM TABLE1
INNER JOIN TABLE2
ON UPPER(master.dbo.fn_sqlvarbasetostr(cast(TimestampColumn as binary(8))))
= VARCHARTIMESTAMPCOLUMN
I've tried:
CONVERT(ROWVERSION, N'0x0000000003306BDD')
No error, but no match on the table (when a row definitely exists).
CONVERT(ROWVERSION, CAST(N'0x0000000003306BDD' as bigint))
This gives an error converting nvarchar
to bigint
.
How can I convert the varchar
value into a timestamp
rather than the other way around?
Best Answer
In SQL Server 2008, converting binary to a character representation became a lot faster and easier:
Notice the style 1 option on the
CONVERT
tochar
. Also, therowversion
type is equivalent tobinary(8)
(when not nullable,varbinary(8)
otherwise).We can now create an index on the computed column:
Add some sample data:
And display the results:
Output example:
The task of joining to the table with
rowversions
in character format is now trivial.SQL Server 2005 version
This requires a helper function:
The table definition becomes:
Everything else proceeds as before, including the index.