Lets say I have 2 tables:
Table Warehouses:
warehouse_id
E4
A9
33
98
23
Table ListOfWarehouses:
warehouses
33,E4,00,23,H3,A9
Assume that there's only going to be 1 record in ListOfWarehouses
. Is there a way to select and order Warehouses
based on the order in ListOfWarehouses
?
So the result should be:
33
E4
23
A9
Alternatively ListOfWarehouses
can also be a variable if that makes it easier. Is there any way to do this?
6条答案
按热度按时间h79rfbju1#
On SQL Server 2008 you can create a set-based ordered string splitting function like this:
This function returns every element in the list (
Value
) along with its position in the list (idx
).Then you can do this (using a variable):
Or this (incorporating the table):
vfh0ocws2#
You can do something like this:
Or alternatively, cross join the warehouse sort table instead of hardcoding list:
The gist of the solution is that find where in the string the warehouse id matches, and then handle non-matches "last".
dpiehjr43#
On SQL Server 2008 you can create a user-defined function
Usage:
Result:
s5a0g9ez4#
All parts seem to be 2 position long:
enxuqcxy5#
Please try the following solution based on XML and XQuery.
No need in a user-defined function (UDF).
SQL
Output
4nkexdtk6#
If we can assume from your sample data warehouse_id is always 2 characters then the following simple criteria might work for you:
Demo Fiddle ;