Skip to content
Advertisement

Optimal join from a column to the concatenation of those columns?

I have a table TableLHS with a column ObjInfo:

ObjInfo
_________
X/132642/A1
X/432753/34
Y/437483/2B

which I would like to join to TableRHS, with columns:

ObjType        ObjNum           ObjFlag
_______        _________        _______
X              00132642         A1
X              00432753         34
Y              00437483         2B

So the join here involves 1) dropping the leading zeroes from ObjNumber, and 2) concatenating the three columns in TableRHS together.

My best shot at the join is:

SELECT ... FROM TableLHS
JOIN TableRHS ON 
        TableLHS.ObjInfo = TableRHS.ObjType + '/' +
        SUBSTRING ( TableRHS.ObjNum, PATINDEX('%[^0]%', TableRHS.ObjNum+'.'), LEN( TableRHS.ObjNum ) ) + 
        '/' + TableRHS.ObjFlag

My current performance could use some improvement. Is there a smarter way of tackling this?

e.g. Is there a more effective way of getting past the leading zeroes in ObjNum? Would it be faster to work the other way round, and try to split ObjInfo on the slashes? Would performing this operation on every row nullify the effect of an index on ObjNum?

Advertisement

Answer

One way to get around the “integers” with leading zeroes would be to do a formal cast to the integer type, then cast back to varchar to use in building the path expression for the join.

SELECT *
FROM TableLHS t1
INNER JOIN TableRHS t2
    ON t1.ObjInfo = t2.ObjType + '/' + CAST(CAST(t2.ObjNum AS INT) AS VARCHAR(12)) +
                    '/' + t2.ObjFlag;

screen capture from demo link below

Demo

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement