BACKGROUND
We have a large routing table that we use to lookup people based on part number (PN).
Routing table:
| PN | Name |
| ------------ | ------------ |
| 51000 | Bob |
| 52000 | Bob |
| 61000 | John |
| 62000 | John |
A given PN will not match routing table exactly. We want it to find the closest solution possible.
Example: SEARCHED_PART_NUMBER = 51235 -> we want script to answer Bob.
Best solution we have found is to recursively search routing table with a loop until we get a hit.
Here is the T-SQL script:
CREATE TABLE #temp_table
(
PN INT,
name VARCHAR(20),
);
DECLARE @Counter INT
SET @Counter = 5
WHILE (@Counter > 0)
BEGIN
INSERT INTO #temp_table
SELECT *
FROM Routing
WHERE LEFT(Routing.PN, @Counter) = LEFT([SEARCHED_PART_NUMBER], @Counter)
IF EXISTS (SELECT * FROM #temp_table)
BEGIN
BREAK;
END
SET @Counter = @Counter - 1
END
SELECT name, COUNT(name) count
FROM #temp_table
GROUP BY name
ORDER BY count
THE ISSUE
Although this code works, it's in the wrong SQL language... DB2 is what this needs to be in. With a ton of effort we have been unable to convert this into something equivalent in DB2 unfortunately.
THE REQUEST
Convert script into a DB2 equivalent
2条答案
按热度按时间n8ghc7c11#
I would use a very different approach in both TSQL and DB2, both will be almost (if not exactly) the same:
Amongst other things (like being simple SQL) this approach will locate any overlapping ranges (so you can do something about them).
DB2 fiddle
nb you could also store the wanted part numbers in a table structure e.g:
2nd DB2 fiddle
& matching TSQL Fiddle
kxe2p93d2#
Equivalent algorithm in Db2 with a single statement.
P - query parameters. 5 is a constant for your 5 digits only PNs.
You may play with different SEARCHED_PART_NUMBER (SPN) at the link below.
fiddle