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))
Related
I need to separate a string in SQL,
Example,
a='001A01-001A05'
What I need in OUTPUT is,
x='001A01'
y='001A05'
Use LEFT, CHARINDEX and SUBSTRING
DECLARE #char VARCHAR(500)= '001A01-001A05'
SELECT LEFT(#char, Charindex('-', #char) - 1),
Substring(#char, Charindex('-', #char) + 1, Len(#char))
Prdp's answer would be my first choice, but if SQL Server 2012+, another option is PARSENAME()
Declare #a varchar(25)='001A01-001A05'
Select x=ParseName(Replace(#a,'-','.'),2)
,y=ParseName(Replace(#a,'-','.'),1)
Returns
x y
001A01 001A05
try this using LEFT and RIGHT
DECLARE #str varchar(max)= '001A01-001A05'
select left(#str, charindex('-', #str)-1),
right(#str, charindex('-', #str)-1)
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).
I have Data in my table which comes like this
Attachements,A,B,C,D.
I just want make this
Attachements:A,B,C,D.
I have tried all the Left,right,LTRIM,RTRIM and Replace functions. this not to deal with spaces
To replace the first comma you can use:
DECLARE #str VARcHAR(100) = 'Attachements,A,B,C,D'
SELECT STUFF(#str, CHARINDEX(',', #str), 1, ':')
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)
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. :)