Replace string SQL - sql

I have a string which is in 99999 124 fdsg format.
I want to replace the first space with - and the next space with a non-space. My expected result will look like this:
99999-124fdsg
To replace the first char I used this expression:
stuff(Product,charindex('',product),1,'-')as trim
Because I want to name the new column as trim. How can I do for the second character?

Charindex has last parameter start_location use it to search for second empty string
Try this
DECLARE #str VARCHAR(50) = '99999 124 fdsg'
SELECT Stuff(Stuff(#str,Charindex(' ',#str),1,'-'),Charindex(' ',#str,Charindex(' ',#str) + 1),1,'')
Result : 99999-124fdsg

Assuming, that you example with STUFF works correctly for the first blank you can just wrap this with REPLACE. After STUFF there's only the other blank left:
replace(stuff(Product,charindex(' ',product),1,'-'),' ','')
Working example:
DECLARE #s VARCHAR(50) = '99999 124 fdsg';
select replace(stuff(#s,charindex(' ',#s),1,'-'),' ','')
The result
99999-124fdsg

Related

Extract Value between two specific varchar

I want to extract numeric value from a varchar in SQL Server 2014
XXXX 0.5Kg I want to return 0.5
XXX 25YY 1.25Kg I want to return 1.25
I want the number between last space from left and Kg
Thanks
You could do
select replace(right(str, charindex(' ',reverse(str))),'Kg','')
from your_table;
DECLARE #string as VARCHAR(MAX) = 'XXX 25YY 1.25Kg'
DECLARE #string_ as VARCHAR(MAX) = 'XXXX 0.5Kg'
SELECT REPLACE(RIGHT(#string, CHARINDEX(' ',REVERSE(#string))),'Kg','')
SELECT REPLACE(RIGHT(#string_, CHARINDEX(' ',REVERSE(#string_))),'Kg','')
First find out the first space in the reverse order of the string and then break the string from that space. the replace the 'kg' from '' to obtain the value that you need. Test the result with many strings. You can use RIGHT string function in SQL to get the specific part from the string.

SQL - How to remove a space character from a string

I have a table where the max length of a column (varchar) is 12, someone has loaded some value with a space, so rather than 'SPACE' it's 'SPACE '
I want to remove the space using a script, I was positive RTRIM or REPLACE(myValue, ' ', '') would work but LEN(myValue) shows there is still and extra character?
As mentioned by a couple folks, it may not be a space. Grab a copy of ngrams8k and you use it to identify the issue. For example, here we have the text, " SPACE" with a preceding space and trailing CHAR(160) (HTML BR tag). CHAR(160) looks like a space in SSMS but isn't "trimable". For example consider this query:
DECLARE #string VARCHAR(100) = ' SPACE'+CHAR(160);
SELECT '"'+#string+'"'
Using ngrams8k you could do this:
DECLARE #string VARCHAR(100) = ' SPACE'+CHAR(160);
SELECT
ng.position,
ng.token,
asciival = ASCII(ng.token)
FROM dbo.ngrams8k(#string,1) AS ng;
Returns:
position token asciival
---------- ------- -----------
1 32
2 S 83
3 P 80
4 A 65
5 C 67
6 E 69
7   160
As you can see, the first character (position 1) is CHAR(32), that's a space. The last character (postion 7) is not a space.
Knowing that CHAR(160) is the issue you could fix it like so:
SET #string = REPLACE(LTRIM(#string),CHAR(160),'')
If you are using SQL Server 2017+ you can also use TRIM which does a whole lot more than just LTRIM-and-RTRIM-ing. For example, this will remove
leading and trailing tabs, spaces, carriage returns, line returns and HTML BR tags.
SET #string = SELECT TRIM(CHAR(32)+CHAR(9)+CHAR(10)+CHAR(13)+CHAR(160) FROM #string)
Odds are it is some other non-printing character, carriage return is a big one when going from between *nix and other OS. One way to tell is to use the DUMP function. So you could start with a query like:
SELECT dump(column_name)
FROM your_table
WHERE column_name LIKE 'SPACE%'
That should help you find the offending character, however, that doesn't fix your problem. Instead, I would use something like REGEXP_REPLACE:
SELECT REGEXP_REPLACE(column_name, '[^A-z]')
FROM your_table
That should take care of any non-printing characters. You may need to play with the regular expression if you expect numbers or symbols in your string. You could switch to a character class like:
SELECT REGEXP_REPLACE(column_name, '[:cntrl:]')
FROM your_table

SQL Server 'LIKE' or varchar issue

I have a stored procedure that searches a table on a column by a string I pass into a varchar.
This works, returns the specific record with the correct ING_LOC_DESCRIPTION
DECLARE #strSearch VARCHAR(500)
SET #strSearch = 'Care1st LETTER Location'
SELECT TOP 10 ING_LOC_DESCRIPTION
FROM [CDRS].[ING_LOC_TRANS_MASTER]
WHERE [ING_LOC_DESCRIPTION] LIKE '%' + #strSearch + '%'
ORDER BY [ING_LOC_ID]
This doesn't work returns the top ten results from all records ordered by ING_LOC_ID:
DECLARE #strSearch VARCHAR(500)
SET #strSearch = '[{"WorkFlowID":"MoveFile"}]'
SELECT TOP 10 ING_LOC_DESCRIPTION
FROM [CDRS].[ING_LOC_TRANS_MASTER]
WHERE [ING_LOC_DESCRIPTION] LIKE '%' + #strSearch + '%'
ORDER BY [ING_LOC_ID]
Are any of these characters [, {, ", :, }, ] invalid in a varchar? Is it being interpreted as 2 strings? Or is it a problem with the LIKE keyword?
The string assignment seems to be ok because
DECLARE #strSearch VARCHAR(500)
SET #strSearch = '[{"WorkFlowID":"MoveFile"}]'
SELECT #strSearch
returns
[{"WorkFlowID":"MoveFile"}]
Unfortunately
DECLARE #strSearch VARCHAR(500)
SET #strSearch = '[{"WorkFlowID":"MoveFile"}]'
SELECT #strSearch LIKE '[{"WorkFlowID":"MoveFile"}]'
Does not return true or false as I had hoped, it returns an error
Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'LIKE'
I think LIKE can only be used in a WHERE clause so I don't think that proves a problem with using LIKE.
Yes. In a LIKE, the [/] bounds a character class. So the code matches any value that contains { or " or W and so on.
I would recommend using a different method:
SELECT TOP 10 ING_LOC_DESCRIPTION
FROM [CDRS].[ING_LOC_TRANS_MASTER]
WHERE CHARINDEX(#strSearch, ING_LOC_DESCRIPTION) > 0
ORDER BY [ING_LOC_ID];
No wildcards in a simple string match.
You need to escape special characters:
List of special characters for SQL LIKE clause
Pattern Matching with the ESCAPE Clause
The [ ] chars has special meaning in T-Sql LIKE - They are used for pattern searches.
For instance: WHERE column LIKE '[a-c]%' will return all records where column starts with a, b or c, while WHERE column LIKE '[^a-c]%' will return all records where Column does not start with a, b or c.
You can escape the [ char by wrapping it inside []: WHERE column LIKE '[[]a]%' will return all records where column starts with [a] (no need to escape the closing bracket).
For more information, read about the arguments of the like operator, and Using Wildcard Characters As Literals a little down the same page.
Gordon's answer is probably the neatest way to do this, but here is an example using ESCAPE:
SELECT TOP 10 ING_LOC_DESCRIPTION
FROM [CDRS].[ING_LOC_TRANS_MASTER]
WHERE [ING_LOC_DESCRIPTION] LIKE '%'+#strSearch+'%' ESCAPE '['
You only need to escape one of the square brackets to avoid the brackets binding a character class.

Replacing all occurrences of a substring in a string in an SQL column except first occurrence

I have a string in a a column text as like below :
Test:HJ,BHS,Test:FG,SKL,Test:KL,PDC
( and so on ...there is no fixed length of this string )
each time Test appears it is followed by Two letters,Three letters ( this is the patter of the string )
Now I want to Replace this string with Test appearing only once like below:
Test:HJ,BHS,:FG,SKL,:KL,PDC
You could use replace like this
DECLARE #Text varchar(500) = 'Test:HJ,BHS,Test:FG,SKL,Test:KL,PDC ( and so on ...there is no fixed length of this string )'
SELECT Replace(#Text, ',' + LEFT(#Text,charindex(':', #Text)), ',:')
Returns
Test:HJ,BHS,:FG,SKL,:KL,PDC ( and so on ...there is no fixed length of this string )

How to replace nth character in sql server

I am trying to replace the nth character in SQL Server. I tried with it using replace():
SELECT REPLACE(ABC,0,1) FROM XXX
In above code all zeros will be replaced with one, but I only want to change it in a particular position and sometimes that position can change.
use stuff
The STUFF function inserts a string into another string. It deletes a specified length of characters in the first string at the start position and then inserts the second string into the first string at the start position.
select STUFF(ABC, starting_index, 1, 'X') from XXX
"Here your int position to replace" is the position no just replace with any int no and that position will be replaced
Note : (Thanks to pcnate for suggestion)
starting_index is your int position to replace.
You're looking for STUFF:
select STUFF(ABC, #n, 1, 'X') from XXX
This would replace the #nth character with an X.
Technically it seeks into the original string at column ABC starting at position #n, deletes 1 character, then inserts the string 'X' at that position.
You use STUFF for this:
SELECT STUFF(ABC, 5, 1, '1')
FROM XXX
This would replace the 5th character with a 1.
Use stuff():
select stuff(abc, 0, 1, 'a')
It is documented here.
Use Stuff.
STUFF(Column_Name,starting_index,
lenth_ofthestring_to_replace_from_starting_index, character_to_replce)
Example_
DECLARE #str varchar(100) = '123456789'
select #str
SELECT STUFF(#str,2,1, 'hello')
-- want to replece 1 charter starting from 2nd position with the string 'hello'
Check this.
SELECT STUFF(#str,2,25, 'hello'),len(#str)