I am trying to extract an OrderID
from a text column in SQL Server. The order number does not always appear in the same place in the column.
Example data shown here:
Bill Jones ORD001234 code 0839 Swindon
ORD01235 - James Brown Code 3838 Norwich
ORD01236, - Jill Scott Code 9838 Glasgow
ORD0123 - Alan Ball - Bath - Code 0879
The ORD00000
value is what I need to extract from the column. However the Order
value can be 7-9 digits in length
This is what I originally tried;
substring ([column], 1, CHARINDEX(' ', [column])) AS OrderNbr
Also gave this a go but the length of the order number did not help. I'm thinking some kind of case statement might work?
,substring([Notes], patindex('%ORD%', [Notes]), 8)
3条答案
按热度按时间nhaq1z211#
One has to wonder why the order number is just dumped into a string with other information and not stored in its own column, or at least why the format isn't standardized.
Part of the problem is that looking for
'%ORD%'
must ignore a name like Frank B***ord***en. The solution must also be able to survive a value withoutORD
at all or with leading garbage right beforeORD
.Here's one way to do that:
And now you know why we tend to follow patterns where each piece of data (like an order number) is stored independently, in its own column: no ugly parsing required. :-)
jdzmm42g2#
Try this:
select substring(substring([Notes], patindex('%ORD%', [Notes]), 10),1,patindex('% %',substring([Notes], patindex('%ORD%', [Notes]), 10))-1)
it first grabs the orderId with extra then clips everything after the space (including the space)syqv5f0l3#
Please try the following solution that is using tokenization instead of parsing.
Notable points:
CROSS APPLY
is tokenizing tokens column as XML..value()
method is retrieving order token, aka order_number.SQL
Output