Search code examples
t-sqlmathprimary-keyuniqueidentifiercomposite-key

Is there a simple way to create a unique integer key from a two-integer composite key?


For various reasons that aren't too germane to the question, I've got a table with a composite key made out of two integers and I want to create a single unique key out of those two numbers. My initial thought was to just concatenate them, but I ran into a problem quickly when I realized that a composite key of (51,1) would result in the same unique key as (5,11), namely, 511.

Does anyone have a clever way to generate an integer out of two integers such that the generated integer is unique to the pair of start integers?

Edit: After being confronted with an impressive amount of math, I'm realizing that one detail I should have included is the sizes of the keys in question. In the originating pair, the first key is currently 6 digits and will probably stay in 7 digits for the life of the system; the second key has yet to get larger than 20. Given these constraints, it looks like the problem is much less daunting.


Solution

  • Multiply one with a high enough value

    SELECT id1 * 1000000 + id2
    

    Or use text concatenation:

    SELECT CAST(CAST(id1 AS nvarchar(10)) + RIGHT('000000' + CAST(id2 AS nvarchar(10)), 6) AS int)
    

    Or skip the integer thing and separate the IDs with something non-numeric:

    SELECT CAST(id1 AS nvarchar) + ':' + CAST(id2 AS nvarchar)