I have a table :
TABLE A
ID (PK)(Identity seed)
Key (nvarchar) (Unique Hashed Keys)
Data:
ID Key
----------- --------------------------------------------------
1 ++0a4rZicJ68kProEpK/ig
2 ++0Coy1S7szg3NjLi2kMLQ
3 ++0eeYiZuRPxsiVVsBcfdg
4 +F07I6n6kLvC/I98So8Y+w
5 +f/RK7VMWIIo5IfUcMujmg
TABLE B : (Without PK)
Content (nvarchar)
SortKey (nvarchar)
Data :
Content SortKey
----------- --------------------------------------------------
TEST1 ++0a4rZicJ68kProEpK/ig
TEST2 ++0Coy1S7szg3NjLi2kMLQ
TEST3 ++0eeYiZuRPxsiVVsBcfdg
TEST4 +F/ZdeGRjbC4sP6ulQnOvg
TEST5 +f0+6vJcwY++Xdx5lch1kQ
TEST6 +f/RK7VMWIIo5IfUcMujmg <-- Expected Result starts here
TEST7 +F07I6n6kLvC/I98So8Y+w
TEST8 +f0990bHYJUOXkyME+0kmg
Query :
SELECT top 3 *
FROM
TABLEB
WHERE
SortKey > (SELECT top 1 Key
FROM TABLEA
ORDER BY ID DESC)
ORDER BY
SortKey
The above query gives me the desired result which is greater than the SortKey (++1l32JdpYoHzXTCIp4jSA):
TEST6 +f/RK7VMWIIo5IfUcMujmg
TEST7 +F07I6n6kLvC/I98So8Y+w
TEST8 +f0990bHYJUOXkyME+0kmg
Once I get this result I need to get the final (last record) key again to do an insert on another table, so I need to get the key of TEST8 in this scenario i.e. : f/RK7VMWIIo5IfUcMujmg.
How do I do this in a single query and not have to write 2 separate queries?
You could use ROW_NUMBER()
DEMO