MS SQL 2012 remove repeated characters from only Right and Left - sql

I need stripe repeated characters from left and right only.
From:
,,,,2000001,2000002,2000003,2000004,2000005,2000006,,,,,
To:
2000001,2000002,2000003,2000004,2000005,2000006

Cheat with trim:
REPLACE(RTRIM(LTRIM(REPLACE(fld, ',', ' '))), ' ', ',')

Use LEFT, SUBSTRING and CHARINDEX string functions
Try this
DECLARE #str VARCHAR(500) = ',,,,2000001,2000002,2000003,2000004,2000005,2000006,,,,,'
SELECT LEFT(intr, Charindex(',,', intr) - 1) as Result
FROM (SELECT Substring(#str, Patindex('%[0-9]%', #str), Len(#str)) AS intr) a

Here is another solution using just REPLACE :) - so funny:
select replace(replace(replace(',,' + YourField + ',,', ',,', '.'), '.,', ''), '.', '')
The character . should not be present in the value of your field, so you can choose any other character meeting that requirement.
This approach is even usable when your field contains spaces (then you cannot play the trick with RTRIM and LTRIM).

Related

Remove single quote before and after the comma

I would like to remove the brackets, single quote before and after the comma from a variable in a elegant way in SQL
DECLARE #str NVARCHAR(MAX);
SET #str = N'(''202102'',''202104'',''202105'',''202106'',''202107'')'
Expected output
'202102,202104,202105,202106,202107'
I have tried and managed to remove the brackets but couldn't progress further for the single quotes.
SELECT SUBSTRING(#str, 2, LEN(#str) - 2); -- '202102','202104','202105','202106','202107'
Also tried the following which removes the whole lot after the first value.
SELECT LEFT(#str, CHARINDEX(',', #str) - 1) -- '202102'
I think this does what you want:
select replace(replace(replace(str, ''',''', ','), '(''', ''), ''')', '')
Here is a db<>fiddle.
Try this char(39) based approach
replace(replace(replace(#str, char(39), ''),'(',char(39)),')',char(39))

How to return only records after certain character?

How to return only records after certain character?
Example:
'1-1080599'
'021-1080599'
'02 -1080599 '
Expected outcome:
'1080599'
This works if you are looking to extract every character after - and if there is only one - character in the string.
select substring(column1,charindex('-',column1)+1,len(column1)) from tablename
where charindex('-',column1) > 0
or RIGHT can be used.
select right(column1,charindex('-',column1)) from tablename
where charindex('-',column1) > 0
vkp's solution will work fine, but you could also use PARSENAME to make things slightly simpler, e.g.:
SELECT PARSENAME(REPLACE('101-2345678', '-', '.'), 1);
If you want to get rid of spaces then you could do this:
SELECT LTRIM(PARSENAME(REPLACE('101 - 2345678', '-', '.'), 1));
...or even:
SELECT PARSENAME(REPLACE(REPLACE('101 - 2345678', '-', '.'), ' ', ''), 1);

SQL Server query to remove the last word from a string

There's already an answer for this question in SO with a MySQL tag. So I just decided to make your lives easier and put the answer below for SQL Server users. Always happy to see different answers perhaps with a better performance.
Happy coding!
SELECT SUBSTRING(#YourString, 1, LEN(#YourString) - CHARINDEX(' ', REVERSE(#YourString)))
Edit: Make sure #YourString is trimmed first as Alex M has pointed out:
SET #YourString = LTRIM(RTRIM(#YourString))
Just an addition to answers.
The doc for LEN function in MSSQL:
LEN excludes trailing blanks. If that is a problem, consider using the DATALENGTH (Transact-SQL) function which does not trim the string. If processing a unicode string, DATALENGTH will return twice the number of characters.
The problem with the answers here is that trailing spaces are not accounted for.
SELECT SUBSTRING(#YourString, 1, LEN(#YourString) - CHARINDEX(' ', REVERSE(#YourString)))
As an example few inputs for the accepted answer (above for reference), which would have wrong results:
INPUT -> RESULT
'abcd ' -> 'abc' --last symbol removed
'abcd 123 ' -> 'abcd 12' --only removed only last character
To account for the above cases one would need to trim the string (would return the last word out of 2 or more words in the phrase):
SELECT SUBSTRING(RTRIM(#YourString), 1, LEN(#YourString) - CHARINDEX(' ', REVERSE(RTRIM(LTRIM(#YourString)))))
The reverse is trimmed on both sides, that is to account for the leading as well as trailing spaces.
Or alternatively, just trim the input itself.
DECLARE #Sentence VARCHAR(MAX) = 'Hi This is Pavan Kumar'
SELECT SUBSTRING(#Sentence, 1, CHARINDEX(' ', #Sentence) - 1) AS [First Word],
REVERSE(SUBSTRING(REVERSE(#Sentence), 1,
CHARINDEX(' ', REVERSE(#Sentence)) - 1)) AS [Last Word]
DECLARE #String VARCHAR(MAX) = 'One two three four'
SELECT LEFT(#String,LEN(#String)-CHARINDEX(' ', REVERSE(#String),0)+1)
All the answers so far are actually about removing a character, not a word as the OP wanted.
In my case I was building a dynamic SQL statement with UNION'd SELECT statements and wanted to remove the last UNION:
DECLARE #sql NVARCHAR(MAX) = ''
/* populate #sql with something like this:
SELECT 1 FROM dbo.T1 WHERE condition
UNION
SELECT 1 FROM dbo.T2 WHERE condition
UNION
SELECT 1 FROM dbo.T3 WHERE condition
UNION
SELECT 1 FROM dbo.T4 WHERE condition
UNION
*/
-- remove the last UNION
SET #sql = SUBSTRING(#sql, 1, LEN(#sql) - PATINDEX(REVERSE('%UNION%'), REVERSE(#sql)) - LEN('UNION'))
SELECT LEFT(username , LEN(json_path) - CHARINDEX('/', REVERSE(username ))+1)
FROM Login_tbl
UPDATE Login_tbl
SET username = LEFT(username , LEN(json_path) - CHARINDEX('/', REVERSE(username ))+1)
DECLARE #String VARCHAR(MAX) = 'One two three four'
SELECT LEFT(#String,LEN(#String)-CHARINDEX(' ', REVERSE(#String),0)+1)

SQL: how to select a substring between special characters

My string looks something like this:
\\\abcde\fghijl\akjfljadf\\
\\xyz\123
I want to select everything between the 1st set and next set of slashes
Desired result:
abcde
xyz
EDITED: To clarify, the special character is always slashes - but the leading characters are not constant, sometimes there are 3 slashes and other times there are only 2 slashes, followed by texts, and then followed by 1 or more slashes, some more texts, 1 or more slash, so on and so forth. I'm not using any adapter at all, just looking for a way to select this substring in my SQL query
Please advise.
Thanks in advance.
You could do a cross join to find the second position of the backslash. And then, use substring function to get the string between 2nd and 3rd backslash of the text like this:
SELECT substring(string, 3, (P2.Pos - 2)) AS new_string
FROM strings
CROSS APPLY (
SELECT (charindex('\', replace(string, '\\', '\')))
) AS P1(Pos)
CROSS APPLY (
SELECT (charindex('\', replace(string, '\\', '\'), P1.Pos + 1))
) AS P2(Pos)
SQL Fiddle Demo
UPDATE
In case, when you have unknown number of backslashes in your string, you could just do something like this:
DECLARE #string VARCHAR(255) = '\\\abcde\fghijl\akjfljadf\\'
SELECT left(ltrim(replace(#string, '\', ' ')),
charindex(' ',ltrim(replace(#string, '\', ' ')))-1) AS new_string
SQL Fiddle Demo2
Use substring, like this (only works for the specified pattern of two slashes, characters, then another slash):
declare #str varchar(100) = '\\abcde\cc\xxx'
select substring(#str, 3, charindex('\', #str, 3) - 3)
Replace #str with the column you actually want to search, of course.
The charindex returns the location of the first slash, starting from the 3rd character (i.e. skipping the first two slashes). Then the substring returns the part of your string starting from the 3rd character (again, skipping the first two slashes), and continuing until just before the next slash, as determined by charindex.
Edit: To make this work with different numbers of slashes at the beginning, use patindex with regex to find the first alphanumeric character, instead of hardcoding that it should be the third character. Example:
declare #str varchar(100) = '\\\1Abcde\cc\xxx'
select substring(#str, patindex('%[a-zA-Z0-9]%', #str), charindex('\', #str, patindex('%[a-zA-Z0-9]%', #str)) - patindex('%[a-zA-Z0-9]%', #str))
APH's solution works better if your string always follows the pattern as described. However this will get the text despite the pattern.
declare #str varchar(100) = '\\abcde\fghijl\akjfljadf\\'
declare #srch char(1) = '\'
select
SUBSTRING(#str,
(CHARINDEX(#srch,#str,(CHARINDEX(#srch,#str,1)+1))+1),
CHARINDEX(#srch,#str,(CHARINDEX(#srch,#str,(CHARINDEX(#srch,#str,1)+1))+1))
- (CHARINDEX(#srch,#str,(CHARINDEX(#srch,#str,1)+1))+1)
)
Sorry for the formatting.
Edited to correct user paste error. :)

What is the most efficient way to RTRIM a STRING without using RTRIM in SQL Server 2005?

In a single-select-statement, I have the need to RTRIM a string in a SQL Server 2005 environment.
What is, in your opinion, the most efficient technique to achieve this?
Examples:
'ALPHA ' ==> 'ALPHA' (the blanks at the end are removed)
' BETA ' ==> ' BETA' (the blank in first position remains, the two blanks at the end are removed)
' GAMMA' ==> ' GAMMA' (the blank in first position remains)
Thank you in advance for your kind help.
EDIT: I am not authorized to use RTRIM!!
Try this
Declare #str Varchar(50) = ' GAMMA '
;With Cte As
(
Select Data = Substring(#str,Number,1)
From master.dbo.spt_values
where Number Between 1 And Len(#str) And Type='P'
)
Select Data = Replace(Bar,' ',' ')
From (Select Cast(Data As Varchar(Max)) From Cte For Xml Path(''))Foo(Bar)
Result
Data
GAMMA
One way as LEN(CHAR_FIELD_OR_VAR) ignores trailing spaces;
left(fld, len(fld))
or
select left(fld, (len(fld + '.')-1)-patindex('%[^ ]%', reverse(fld))+1)
Select rtrim(ltrim(col)) from....
That will trim both sides of the column
I think your answer is in the title:
SELECT Columm1
, RTRIM(Column1) as Column1Trimmed
FROM Table1
RTRIM is the most efficient method of Right TRIMming.
Without RTRIM:
select '* *'
, REPLACE('* *',' ','')