SQL View SUBSTRING and CHARINDEX - sql

I have a query in SQL 2008
SELECT [orde_reference],
SUBSTRING([orde_reference],
CHARINDEX('/', [orde_reference]) + 1,
LEN([orde_reference])) AS batch
FROM Orders
That returns the following
orde_reference: 27777/2012/1
batch: 2012/1
However I need the batch to just be the characters after the last / (there are always 2 x '/' in the varchar
orde_reference: 27777/2012/1
batch: 1
Any help would be appreciated.
Cheers
Mim

Try
SELECT orde_reference,
RIGHT(orde_reference, CHARINDEX('/', REVERSE(orde_reference)) - 1) batch
FROM orders
Sample output:
| ORDE_REFERENCE | BATCH |
--------------------------
| 27777/2012/1 | 1 |
| 27734/2013/11 | 11 |
Here is SQLFiddle demo

As there are always 2 / you can pass the optional third argument to CHARINDEX (start_location) to tell it to start looking after the first one.
SELECT [orde_reference],
SUBSTRING([orde_reference],
CHARINDEX('/', [orde_reference],1 + CHARINDEX('/', [orde_reference])) + 1,
LEN([orde_reference])) AS batch
FROM Orders
You would be better off storing these components individually however in separate columns.

Use REVERSE twice ;)
SELECT [orde_reference]
,REVERSE(SUBSTRING(reverse([orde_reference]), 0, CHARINDEX('/', reverse([orde_reference])))) AS batch
from (values(
' 27777/2012/123'
)) as O([orde_reference])

Related

Wildcards using LTRIM in SQL Lite

I'm trying to use LTRIM to split the following field 'hours' - trimming off the characters from the left up to and including the pipe | symbol.
Monday|11:00-18:00
to result in
11:00-18:00
I would have thought the following code is correct
LTRIM(hours, '%|')
But it just isn't working. The query runs but the above statement has no affect. Can anyone help?
Many thanks
Richard
Use instr() to compute the position of the pipe character in the string, and substr() to select everything after that position:
substr(col, instr(col, '|') + 1) as newcol
Demo on DB Fiddle:
with t as (select 'Monday|11:00-18:00' col)
select substr(col, instr(col, '|') + 1) as newcol from t
| newcol |
| :---------- |
| 11:00-18:00 |

Add Trailing Zeroes After Decimal

I am working with sku numbers that have the following 9 character structure:
a. a 3 digit number,
b. a period,
c. a five digit number.
An example: 505.12345.
A considerable % of the sku's end in 0. Examples: 505.12340, 505.12300, 505.12000.
I had no trouble keeping the trailing zeroes in SQL Server by setting the datatype to varchar after the migration from S3 -> SQL Server. I used a new machine learning model in AWS Sagemaker that cut off the trailing zeroes prior to the migration to S3.
The example sku's above now look like: 505.1234, 505.123, 505.12
My question: what is the best way to add trailing zeroes to all sku's where LEN([sku]) < 9? I would prefer to keep the sku datatype as varchar.
If you have a string, you can right-pad it with 0s as follows:
left(sku + replicate('0', 9), 9)
Alternatively:
sku + replicate('0', 9 - len(sku))
Demo on DB Fiddle:
select sku,
left(sku + replicate('0', 9), 9) new_sku,
sku + replicate('0', 9 - len(sku)) new_sku2
from (values ('505.1234'), ('505.123'), ('505.12'), ('505.12345')) x(sku)
sku | new_sku | new_sku2
:-------- | :-------- | :--------
505.1234 | 505.12340 | 505.12340
505.123 | 505.12300 | 505.12300
505.12 | 505.12000 | 505.12000
505.12345 | 505.12345 | 505.12345
One simple way would be to CAST back to DECIMAL(9, 5) and then CAST again to CHAR(9)
Data
drop table if exists #tTable;
go
create table #tTable(
dec_num varchar(20) not null);
Insert into #tTable values
('505.1234'),
('505.123'),
('505.12');
Query
select cast(cast(dec_num as decimal(9,5)) as char(9)) char_9
from #tTable;
Output
char_9
505.12340
505.12300
505.12000

How to trim data with last alphanumeric key as reference

Need your help on below Data trimming or what so ever to get the result that shows also on below. I want to get the data where my reference is the last - symbol.
See example below.
FROM TO
+-------------------------------+
|ABC-1234-AR-R | ABC-1234-AR |
|ABC-1254-AR-IT | ABC-1254-AR |
|ABC-1223-AR-LTL| ABC-1223-AR |
|ABC-1234-R | ABC-1234 |
+-------------------------------+
This will give you index of last occurence of a hyphen:
LEN(data) - CHARINDEX('-', REVERSE(data)) + 1
So it's enough to take substring of this length:
SELECT
data,
SUBSTRING(data, 1, LEN(data) - CHARINDEX('-', REVERSE(data))) AS data_trimmed
FROM yourTable;
Demo
You can also use a combination of LEFT and CHARINDEX functions.
Query
select [from],
left([from], len([from]) - charindex('-', reverse([from]), 1)) as [to]
from [your_table_name];
Find a demo here

Syntax error or access violation when using STRPOS with semicolon character

I have a table table1 with the following data
+----------------+
| model |
+----------------+
| a45/ a45m;aa45 |
| b34/b34m |
| c23;c23m/ cc23 |
+----------------+
I'm trying to clean up the model field with certain rules, such as
grab all characters before the first ;
from 1, grab all character before the first /
So I do the following in netezza for step 1
SELECT
SUBSTR(model, 1, STRPOS(model, ';')-1) AS model_clean
FROM table1
;
This throws error ERROR [42000] Syntax error or access violation. Any ideas why this is happening, does the character ; need to be escaped ?
One thing to note is that When I look for the space character as following, there is no error.
SELECT
SUBSTR(model, 1, STRPOS(model, ' ')-1) AS model_clean
FROM table1
;
Also is there a way to get step 2 also done in this same select statement ?
Expected output
+----------------+
| model_clean |
+----------------+
| a45 |
| b34 |
| c23 |
+----------------+
It fails because not all columns have semicolons, so strpos() returns 0. You can fix this just by adding a semicolon:
SELECT SUBSTR(model, 1, STRPOS(model || ';', ';') - 1) AS model_clean
Your query fails when you try to do substring with an invalid position, the result of strpos wich didn't found the semicolon.
You can use case statement to avoid calculate invalid position
Here are an example of SQLServer syntaxe ( charindex and strpos have reversed parameter order, up to you to reduce the query) http://sqlfiddle.com/#!18/55a6e/25
WITH step1
AS ( SELECT CASE
WHEN CHARINDEX(';', model) > 0 THEN SUBSTRING(model, 1, CHARINDEX(';', model) - 1)
ELSE model
END AS model
FROM table1 ),
step2
AS ( SELECT CASE
WHEN CHARINDEX('/', model) > 0 THEN SUBSTRING(model, 1, CHARINDEX('/', model) - 1)
ELSE model
END AS model
FROM step1 )
SELECT *
FROM step2;

How to use substring and PatIndex in SQL Server

How to substring data. For example, I have data like this:
+----------------------+
|John123123412412wqeqw |
|May1231243334234wawdd |
|Jo02930124010284jahdj |
|dy827837127912938hygb |
+--------------------- +
I want the output to be like this:
+----------------------+
|John |
|May |
|Jo |
|dy |
+--------------------- +
As of now I don't understand how to Apply Substring and charindex in my script.
Thanks in advance!
You can try LEFT and PATINDEX with a pattern to match the numbers like PATINDEX('%[0-9]%', 'John123123412412wqeqw').
Sample code
DECLARE #Text VARCHAR(500);
SET #Text = 'John123123412412wqeqw';
SELECT LTRIM(RTRIM(LEFT(#Text, PATINDEX('%[0-9]%', #Text) - 1)))
You can do this from the table as below
SELECT
LTRIM(RTRIM(LEFT(ColumnName, PATINDEX('%[0-9]%', ColumnName) - 1)))
FROM
[Table1]
Best way to handle the strings and there manipulation is in application side and not in database side. But if you required this then you can use PATINDEX along with SUBSTRING to get what you want,
SELECT PATINDEX('%[^0-9]%',stringValueCol) 'Position of NonNumeric String Position',
SUBSTRING(stringValueCol,PATINDEX('%[^0-9]%',stringVlaueCol),PATINDEX('%[^A-Z]%',stringValueCol)-1) 'NonNumeric String'
FROM
myTable
But I would still suggest do this manipulations in code and not on database side.