I want to remove the value after *.*, but it the value of the length is not definite - sql

Thank you in advance.
I want to remove the values after ., but the length is not defined it keeps changing but it should not take the values after the second FULL STOP.
1)Example:
Input:- ROL0602.E.DCM.5264403 and COK0105.F.SKE and CLT005.02A.FCM.65721
output: ROL0602.E and COK0105.F and CLT005.02A
2) example :
Input: SKE-5700-00211-000
output: SKE-5700-00211
These are the two columns i want some help with.
I tried using the charindex but as the length keeps on changing i wasn't able to do it.

Try it like this:
DECLARE #tbl TABLE(YourValue VARCHAR(100));
INSERT INTO #tbl VALUES
('ROL0602.E.DCM.5264403'),('COK0105.F.SKE'),('CLT005.02A.FCM.65721'),('SKE-5700-00211-000');
SELECT CASE WHEN CHARINDEX('.',YourValue)>0 THEN LEFT(YourValue,CHARINDEX('.',YourValue,CHARINDEX('.',YourValue,1)+1)-1)
ELSE YourValue END
FROM #tbl AS tbl
The result
ROL0602.E
COK0105.F
CLT005.02A
SKE-5700-00211-000
Please provide a rule for the last example. Don't know how to cut this...
This command uses LEFT to take a string starting at the beginning. The lenght is found by searching for a dot, starting at the position 1 after the first dot.
UPDATE: A more generic solution
The following fill first split the string in its parts (easy to use with other separators too). This is finally re-concatenated depending on a rule you can define yourself:
DECLARE #tbl TABLE(YourValue VARCHAR(100));
INSERT INTO #tbl VALUES
('ROL0602.E.DCM.5264403'),('COK0105.F.SKE'),('CLT005.02A.FCM.65721'),('SKE-5700-00211-000');
WITH Parted AS
(
SELECT YourValue
,CAST('<x>' + REPLACE(REPLACE(tbl.YourValue,'-','.'),'.','</x><x>') + '</x>' AS XML) AS Casted
,CASE WHEN CHARINDEX('.',YourValue)>0 THEN '.' ELSE CASE WHEN CHARINDEX('-',YourValue)>0 THEN '-' ELSE '?' END END AS SeparatorChar
FROM #tbl AS tbl
)
,SingleParts AS
(
SELECT SeparatorChar
,YourValue
,ISNULL(Casted.value('/x[1]','nvarchar(max)'),'') AS Part1
,ISNULL(Casted.value('/x[2]','nvarchar(max)'),'') AS Part2
,ISNULL(Casted.value('/x[3]','nvarchar(max)'),'') AS Part3
,ISNULL(Casted.value('/x[4]','nvarchar(max)'),'') AS Part4
,ISNULL(Casted.value('/x[5]','nvarchar(max)'),'') AS Part5
FROM Parted
)
SELECT CASE SeparatorChar
WHEN '.' THEN Part1 + '.' + Part2
WHEN '-' THEN Part1 + '-' + Part2 + '-' + Part3
ELSE YourValue
END
FROM SingleParts
The result
ROL0602.E
COK0105.F
CLT005.02A
SKE-5700-00211

SHnugo's solution is excellent but will fail if there is only one dot (.) in the string. Here's a tweaked version that will handle that (note my comments).
DECLARE #tbl TABLE(YourValue VARCHAR(100));
INSERT INTO #tbl VALUES
('ROL0602.E.DCM.5264403'),('COK0105.F.SKE'),('CLT005.02A.FCM.65721'),('CLT099.02ACFVVV721'), ('SKE-5700-00211-000');
SELECT
CASE
--If there are two or more dots(.) then return everything up to the second dot:
WHEN LEN(YourValue) - LEN(REPLACE(YourValue,'.','')) > 1
THEN LEFT(YourValue,CHARINDEX('.',YourValue,CHARINDEX('.',YourValue,1)+1)-1)
ELSE YourValue -- if there are 1 or 0 dots(.) then return the entire value
END
FROM #tbl AS tbl;

You can try as follows:
SELECT REPLACE('ROL0602.E.DCM.5264403',
( '.' + REVERSE(SUBSTRING(REVERSE('ROL0602.E.DCM.5264403'), 0,
CHARINDEX('.',
REVERSE('ROL0602.E.DCM.5264403')))) ),
'')

Related

SQL: select the last values before a space in a string

I have a set of strings like this:
CAP BCP0018 36
MFP ACZZ1BD 265
LZP FEI-12 3
I need to extract only the last values from the right and before the space, like:
36
265
3
how will the select statement look like? I tried using the below statement, but it did not work.
select CHARINDEX(myField, ' ', -1)
FROM myTable;
Perhaps the simplest method in SQL Server is:
select t.*, v.value
from t cross apply
(select top (1) value
from string_split(t.col, ' ')
where t.col like concat('% ', val)
) v;
This is perhaps not the most performant method. You probably would use:
select right(t.col, charindex(' ', reverse(t.col)) - 1)
Note: If there are no spaces, then to prevent an error:
select right(t.col, charindex(' ', reverse(t.col) + ' ') - 1)
Since you have mentioned CHARINDEX() in question, I am assuming you are using SQL Server.
Try below
declare #table table(col varchar(100))
insert into #table values('CAP BCP0018 36')
insert into #table values('MFP ACZZ1BD 265')
insert into #table values('LZP FE-12 3')
SELECT REVERSE(LEFT(REVERSE(col),CHARINDEX(' ',REVERSE(col)) - 1)) FROM #table
Functions used
CHARINDEX ( expressionToFind , expressionToSearch ) : returns position of FIRST occurence of an expression inside another expression.
LEFT ( character_expression , integer_expression ) : Returns the left part of a character string with the specified number of characters.
REVERSE ( string_expression ) : Returns the reverse order of a string value

Best way to pad section of this string with 0s

This is 2 examples of what the string currently look like:
6731-121-1
9552-3-1
This is what I want to pad them to look like
0006731-121-1
0009552-003-1
So I want them to be padded with 7 zeroes before the first '-' then 3 zeroes between the first and second '-'
What would be the best way to accomplish this in SQL SELECT statement.
SELECT RIGHT('0000000'
+ ISNULL(
LEFT(OE.exception_id, CHARINDEX('-', OE.exception_id)
- 1) ,
''
) ,7) + '-'
+ SUBSTRING(OE.exception_id, CHARINDEX('-', ( OE.exception_id )), 10) exception_id
ParseName() could be an option here
Example
Declare #YourTable Table ([YourCol] varchar(50))
Insert Into #YourTable Values
('6731-121-1')
,('9552-3-1')
Select *
,NewVal = right('0000000'+parsename(replace(YourCol,'-','.'),3),7)
+'-'
+right('000'+parsename(replace(YourCol,'-','.'),2),3)
+'-'
+parsename(replace(YourCol,'-','.'),1)
From #YourTable
Returns
YourCol NewVal
6731-121-1 0006731-121-1
9552-3-1 0009552-003-1
In situations with more than 3 periods
Example: '1.2.3.4.5'
Or any value is empty
3 examples: '1..3', '1.2.3.', '.2'
Parsename will return null for all values. You will need to split the column using a different method.
Here is an alternative to parsename:
DECLARE #table table(col varchar(100))
INSERT #table values('6731-121-1'),('9552-3-1')
SELECT
col,
REPLICATE('0', 8-x) + STUFF(col, x+1, 0,REPLICATE('0', 4 - (y-x))) newcol
FROM #table
CROSS APPLY
(SELECT CHARINDEX('-', col) x) x
CROSS APPLY
(SELECT CHARINDEX('-', col + '-', x+1) y) y
col newcol
6731-121-1 0006731-121-1
9552-3-1 0009552-003-1

SQL Server substring w/o custom functions

I have a dilemma regarding how to extract a sub string from a larger string without using custom functions
The string is of this form:
" [1].[2]"
" [1].[2].[3]"
" [1].[2].[3].[4]"
Basically, it's a hierarchy that has 4 leading spaces for every child of a node. The task is to maintain those 4 leading spaces for every node, but get only the child in the end, without the full path
So, the final result should be something like this:
" [2]"
" [3]"
" [4]"
Could anyone help me?
Edit: or, if it's the case, should I modify the CTE that is building the result set?
The CTE is like the one below:
WITH Hierarchy(cid, cname, parent_id, Parents, nname)
AS
(
SELECT map_id, name, parent_id, CAST('' AS VARCHAR(MAX)), CAST(''+name AS VARCHAR(MAX))
FROM tblMapping AS tm1
WHERE parent_id = 0
UNION ALL
SELECT tm.map_id, tm.name, Parent.cid,
CAST(CASE WHEN Parent.Parents = ''
THEN(CAST(tm.parent_id AS VARCHAR(MAX)))
ELSE(Parent.Parents + '.' + CAST(tm.parent_id AS VARCHAR(MAX)))
END AS VARCHAR(MAX)),
-- add the formated column description
CAST(CASE WHEN Parent.Parents = ''
THEN(Parent.cname)
ELSE(' '+Parent.nname+ '.'+tm.name)
END AS VARCHAR(MAX))
FROM tblMapping AS tm
INNER JOIN Hierarchy AS Parent ON tm.parent_id = Parent.cid
)
SELECT *
FROM Hierarchy
ORDER BY ltrim(nname)
OPTION(MAXRECURSION 32767)
Thank you!
Try something like this
UPDATED: Inlcudes a root node now...
DECLARE #mockup TABLE(YourString VARCHAR(100));
INSERT INTO #mockup VALUES
(' [1]')
,(' [1].[2]')
,(' [1].[2].[3]')
,(' [1].[2].[3].[4]');
SELECT LEFT(YourString,CHARINDEX('[',YourString)-1)
+SUBSTRING(YourString,LEN(YourString)+1-CHARINDEX('[',REVERSE(YourString)),1000)
FROM #mockup;
I would concatenate the spaces part with the last index.
Something like
Select left(your_string, char_index(your_string, "[") - 1) +
right(your_string, 3) from your_table
The 3 is assuming there's always one digit. If not, this is a bit complex because no last index of in SQLServer:
Select left(your_string, char_index(your_string, "[") - 1) +
reverse(left(reverse(your_string), char_index(reverse(your_string), "[")))
from your_table

Calculate amount of text

message
------------
01d,2s3,1wee (nvarchar)
01,32,32154, (nvarchar)
df,g,d, (nvarchar)
dd,12,2 (nvarchar)
I dont know how to achieve the result below and to take account to the ',' in the end of the cell. The data in the list can be changed daily.
Requested result
message Count
------------ -----
01d,2s3,1wee 3
01,32,32154, 3
df,g,d, 3
dd,12,2 3
// DWD
declare #table table(message varchar(20))
insert into #table values('01d,2s3,1wee');
insert into #table values('01,32,32154,');
insert into #table values('df,g,d,');
insert into #table values('dd,12,2');
SELECT message
,CASE WHEN SUBSTRING(REVERSE(message),1,1) = ',' THEN
LEN(message) - LEN(REPLACE(message, ',', '')) ELSE
( LEN(message) - LEN(REPLACE(message, ',', '')) +1 )END As Count
FROM #table
This approach checks if the final character is a ,, and then removes it if it is...
it then compares the length of the original message to the length of the message with all , removed to determine how many , existed originally.
select
len(message) - len(replace(message, ',', '')) as wordCount
from
(
select
case
when right(rtrim(message),1) = ','
then substring(rtrim(message),1,len(rtrim(message))-1)
else message
end as message
) trimmed
I think this is what you are looking for:
SELECT message
,[Count] = LEN(CASE WHEN RIGHT(message, 1) = ',' THEN message ELSE message + ',' END) - LEN(REPLACE(CASE WHEN RIGHT(message, 1) = ',' THEN message ELSE message + ',' END, ',' ,''))
FROM yourtablename
First, You need to get rid of the trail ",", and then count the length of the original string and substract the length of the string replacing "," with nothing. Something like this:
SELECT message, LEN(Newmessage) - LEN(REPLACE(Newmessage,',','')) + 1 [Count]
FROM (SELECT message, CASE WHEN RIGHT(message,1) = ',' THEN LEFT(message,LEN('01,32,32154,')-1) ELSE
message END AS Newmessage
FROM YourTable) A
This assumes that there is no trailing spaces on your columns, otherwise you should use RTRIM
SELECT message
, 1 + LEN(message) - REPLACE ( message , ',' , '' ) AS count
FROM my_table
The tick consists in counting the number of comas (",") in the column.
For this, it calculates the difference between the string and the same string without the coma.

SQL, remove appearances of a comma at end of the comma seperated list

How can we remove last comma from a comma seperated list in SQL query?
I have done a sample where i get a comma seperated string as output. But i found that a comma is comming after the string ends. I have tried to trim it of but was not able to do it.Can any one help me in getting it off?
my resulting string looks like this
eg:- some text, some more text, even more, yet more,
DECLARE #my_string nvarchar(128)
SET #my_string = N'Some Text, Some More Text, Even More, Yet More,'
select SUBSTRING(#my_string, 1, LEN(#my_string) - 1)
Should you need further assistance, you should provide further information.
Update MyTable
Set MyField = Case
When Right(MyField,1) = ',' Then Substring( MyField, 1, Len(MyField) - 1 )
Else MyField
End
Btw, another alternative:
Update MyTable
Set MyField = Substring( MyField, 1, Len(MyField) - 1 )
Where Value Like '%,'
Test script:
Declare #TestValues Table ( Value nvarchar(100) not null )
Insert #TestValues(Value) Values( 'XYZZY' )
Insert #TestValues(Value) Values( 'PLUGH' )
Insert #TestValues(Value) Values( 'SpiffyValueWithComma,' )
Select Case
When Right(Value,1) = ',' Then Substring( Value, 1, Len(Value) - 1 )
Else Value
End
From #TestValues
Results:
XYZZY
PLUGH
SpiffyValueWithComma
Update
One possibiity is that your trailing value isn't a comma but rather a comma and a space. If that's the case, then you need to modify your query like so:
Update MyTable
Set MyField = Substring( MyField, 1, Len(MyField) - 1 )
Where Value Like '%,'
Or Value Like '%, '