SQL QUERY to bring last letter in a string to first letter position using SQL Server - sql

I have a column called Supervisor from a table JobData in a SQL Server database. In this Supervisor column the records are of the format below.
DANNYL
ADITYAG
SAMMYS
BOBBYJ
I want to convert these records to lower case and bring the last letter to first letter. For example, DANNYL should be changed to the format ldanny and this format should be applied to all the remaining records.
Can anyone help me out with a SQL query for this?

You can use the following solution using LEFT and RIGHT to get the parts of the name. By using LOWER you can convert the upper case characters to lower case:
SELECT LOWER(RIGHT(Supervisor, 1) + LEFT(Supervisor, LEN(Supervisor) - 1))
FROM JobData
WHERE LTRIM(RTRIM(Supervisor)) <> ''
-- or using ABS on the length - 1 so the WHERE isn't needed.
SELECT LOWER(RIGHT(Supervisor, 1) + LEFT(Supervisor, ABS(LEN(Supervisor) - 1)))
FROM JobData
Since it looks like the column Supervisor contains empty values you can also use the following solution without calculation and not failing on the empty values:
SELECT LOWER(RIGHT(Supervisor, 1) + REVERSE(SUBSTRING(REVERSE(Supervisor), 2, LEN(Supervisor))))
FROM JobData
... and another possibility using STUFF:
SELECT LOWER(LEFT(STUFF(Supervisor, 1, 0, RIGHT(Supervisor, 1)), LEN(Supervisor)))
FROM JobData
demo on dbfiddle.uk

there is probably a better way do to that , but here is my proposition.
SELECT lower(left(right('DANYL',1)+'DANYL',len('DANYL')))

Using SUBSTRING you can get the expected result:
SELECT LOWER(CONCAT(SUBSTRING(Supervisor, LEN(Supervisor), 1), SUBSTRING(Supervisor, 0, LEN(Supervisor))))
FROM JobData
Demo with the given sample data:
DECLARE #JobData TABLE (Supervisor VARCHAR(100));
INSERT INTO #JobData (Supervisor) VALUES
('DANNYL'), ('ADITYAG'), ('SAMMYS'), ('BOBBYJ');
SELECT LOWER(CONCAT(SUBSTRING(Supervisor, LEN(Supervisor), 1), SUBSTRING(Supervisor, 0, LEN(Supervisor)))) AS Supervisor
FROM #JobData
Output:
ldanny
gaditya
ssammy
jbobby

Like this? :
SELECT
LOWER(CONCAT(SUBSTRING([Supervisor], LEN([Supervisor]), 1),SUBSTRING([Supervisor], 1, ABS(LEN([Supervisor])-1))))
FROM TABLE

Related

TSQL extract part of string with regex

i would make a script that iterate over the records of a table with a cursor
and extract from a column value formatted like that "yyy://xx/bb/147011"
only the final number 147011and to put this value in a variable.
It's possible to do something like that?
Many thanks.
You don't need a cursor for this. You can just use a query. The following gets everything after the last /:
select right(str, charindex('/', reverse(str)) - 1 )
from (values ('yyy://xx/bb/147011')) v(str)
It does not specifically check if it is a number, but that can be added as well.
You can also use the below query.
SELECT RIGHT(RTRIM('yyy://xx/bb/147011'),
CHARINDEX('/', REVERSE('/' + RTRIM('yyy://xx/bb/147011'))) - 1) AS LastWord
If numeric value has exact position defined with sample data, then you can do :
SELECT t.*, SUBSTRING(t.col, PATINDEX('%[0-9]%', t.col), LEN(t.col))
FROM table t;

How can I extract part of a string with different lengths and insert it into a table?

I uploaded some data from excel sheet to a table in sql , I would like to use part of the string that I inserted into the column PPRName and insert into another table [Verify].
The data in the column when inserted looks like this:
August 2018 [ NW: Construction MTP021 - Building and Civil Construction: Masonry NQF 3 ]
I want to insert this part of the string :
NW: Construction MTP021 - Building and Civil Construction: Masonry NQF 3
into another table [Verify] for every PPR Name in the PPRName column. The names of the PPRs vary in length but all come in same format.
I would also like to extract the August 2018 and cast it as a date and insert into my table [Verify].
I am not sure how to use Charindex and Substrings to achieve this.
i tried this but no data was returned
select SUBSTRING([PPR_Caption],charindex('[',[PPR_Caption]),charindex([PPR_Caption],']'))
FROM [dbo].[PPRS]
You incorrectly use the 2nd CHARINDEX and you incorrectly use the SUBSTRING commands.
SELECT SUBSTRING(PPR_Caption, CHARINDEX("[", PPR_Caption) + 1, CHARINDEX("]", PPR_Caption) - CHARINDEX("[", PPR_Caption) - 1)
FROM PPRS
SUBSTRING uses a start and a lenght, not the start and end point. To get the length use your end point and substract the start point (and correct the 1 position offset with -1).
In your 2nd CHARINDEX you switched the string to search in and the string to look for.
String operations like this are cumbersome in SQL Server.
Try this:
select replace(v2.str_rest, ' ]', '') as name, cast(str_start as date) as dte
from (values ('August 2018 [ NW: Construction MTP021 - Building and Civil Construction: Masonry NQF 3 ]')
) v(str) cross apply
(values (stuff(v.str, 1, charindex('[', str) + 1, ''), substring(v.str, 1, charindex('[', str) -1))
) v2(str_rest, str_start);
SQL Server is pretty good about guessing formats for converting dates, so it will actually convert the date without the day of the month.

get last _ position values in sql server

Hi I have one doubt in sql server .
how to get first position to right side specific character position.
table : empfiles
filename:
ab_re_uk_u_20101001
ax_by_us_19991001
abc_20181002
I want output like below:
filename
ab_re_uk_u
ax_by_us
abc
I tried like below :
select SUBSTRING(filename,1,CHARINDEX('2',filename) - 1) as filename from empfiles
above query is not given expected result please tell me how to write query to achive this task in sql server .
If last position has always numeric values then you can use patindex():
select *, substring(filename, 1, patindex('%[0-9]%', filename)-2) as NewFile
from empfiles e;
If you want to get characters after than _ to right sight of string then you can use combo to reverse() and substring()
select *,
reverse(substring(reverse(filename),charindex('_', reverse(filename))+1, len(filename)))
from empfiles e;
Another way is to use reverse in combination with STUFF.
create table f(filename nvarchar(100));
insert into f values
('ab_re_uk_u_20101001')
,('ax_by_us_19991001')
,('abc_20181002');
select
filename=reverse(stuff(reverse(filename),1,charindex('_',reverse(filename)),''))
from f
Try This
CREATE TABLE #DATA([FILENAME] NVARCHAR(100));
INSERT INTO #DATA VALUES
('ab_re_uk_u_20101001')
,('ax_by_us_19991001')
,('abc_20181002');
SELECT [filename],
SUBSTRING([filename],0,PATINDEX('%[0-9]%',[filename])-1) AS ExpectedResult
FROM #Data
Result
filename ExpectedResult
--------------------------------------
ab_re_uk_u_20101001 ab_re_uk_u
ax_by_us_19991001 ax_by_us
abc_20181002 abc
Well, obviously the last position value is a date, and the format is YYYYMMDD so its 8 characters, plus, added by underscore character, so that makes its 9 character.
Assumed by the above statement applied, the following logic of the query should work
SELECT SUBSTRING(ColumnText, 1, LEN(ColumnText) - 9)
Which means, only display characters from character position 1, to character position LEN - 9, which LEN is the length of characters, and 9 is the last 9 digit of number to be removed
Try with this ..
select [filename],SUBSTRING([filename],1,PATINDEX('%_[0-9]%',[filename])-1) from empfiles
Individual Select records
SELECT SUBSTRING('ab_re_uk_u_20101001',1,PATINDEX('%_[0-9]%','ab_re_uk_u_20101001')-1)
SELECT SUBSTRING('ax_by_us_19991001',1,PATINDEX('%_[0-9]%','ax_by_us_19991001')-1)
SELECT SUBSTRING('abc_20181002',1,PATINDEX('%_[0-9]%','abc_20181002')-1)

Max of a part of split string

I have, in my DB oracle 10g, a field that contains references.
It's stored as : name/yyyy/mm/number
The new number, is the max number found in the part mm/number.
So, for now, I have a split of my string that gives me a list of str_array like this :
str_array(name, yyyy, mm, number)
I'd like, with this, found max number, for the couple mm/number.
Is this possible to do this?
Can I have something like :
SELECT MAX(split(reference, '/').lastPartOfArray) into nb
FROM table
where lastPartOfArray-1 = sysdate.month;
Data samples :
Smith/2013/12/1
Smith/2013/11/1
Smith/2013/12/3
Jones/2013/12/6
Smith/2013/12/3
Jones/2013/11/7
Since we are in the month 12, a max on those data must give me 6 into nb.
The number part, has no limit, it can be 1000, 10000...
The part Jones/2013 doesn't really matter for the number. But I can't have the same number, for a month.
My apologies, I don't know if this is possible, so I tried to write what I want in the query.
Is this possible, or should I create more than one field in my table(name/yyyy, mm, number)?
edit : valex answer and some custom
select MAX(CAST(SUBSTR(num,INSTR(num,'/')+9,1000) as Int))
from T
where num like TO_CHAR(sysdate,'%/YYYY/MM/%')
So this, count searching first occurence.
select MAX(CAST(SUBSTR(num,INSTR(num,'/',1 ,n)+1,1000) as Int))
from T
where num like TO_CHAR(sysdate,'%/YYYY/MM/%')
This found the n occurence of the char.
This is a helpful solution in other cases.
To get a maximum you should convert this last part into INT values otherwise you can get not right results because of STRING comparing rules will be used.
As soon as /YYYY/MM/ has got a fixed length = 9 so we can find first \ position and add 9 to this position to find a last part number substring start.
Here is an example:
select MAX(CAST(SUBSTR(num,INSTR(num,'/')+9,1000) as Int))
from T
where num like TO_CHAR(sysdate,'%/YYYY/MM/%')
SQLFiddle demo
Also you can exclude wrong formatted values from this query to avoid conversion errors using the following way:
select MAX(CAST(SUBSTR(num,INSTR(num,'/')+9,1000) as Int))
from T
where num like TO_CHAR(sysdate,'%/YYYY/MM/%')
AND
LENGTH(TRIM(TRANSLATE(SUBSTR(num,INSTR(num,'/')+9,1000),
' 0123456789', ' '))) is null
SQLfiddle demo
Try this:
SELECT
MAX(SUBSTR(num, INSTR(num, '/', 1, 3) + 1))
FROM ref
WHERE
SUBSTR(num, INSTR(num, '/', 1, 2) + 1, INSTR(num, '/', 1, 3) - INSTR(num, '/', 1, 2) - 1) = TO_CHAR(sysdate, 'MM')
Sample: http://sqlfiddle.com/#!4/1b03a/1

SQL query to remove left and right characters in a field

I have a sql field that i need to edit out characters on the left and right.
The table name is: cdr
The field name is: dstchannel
The dstchannel field shows the following data: Local/872#from-internal-6acb,1
I just the need the 872 as output
The field always has the same amount of data, so the 872 will be constaint on its position.
How would I go about writing a sql query for mysql?
If I have another query that I want to include this into, how would I do that?
Thank you
Assuming the number is always 3 characters in length:
SELECT
SUBSTRING(dstchannel, 7, 3) AS x
FROM cdr
If the length of the number is variable, you'll need to look for the '#'. In T-SQL (SQL Server), you can use CHARINDEX:
SELECT
SUBSTRING(dstchannel, 7, CHARINDEX('#', dstchannel, 7) - 7) AS x
FROM cdr
If the delimiters are always '/' and '#':
select substring(dstchannel,
locate('/', dstchannel) + 1,
locate('#', dstchannel) - locate('/', dstchannel) - 1);