Replace characters from given string - sql

String = "Vishal Hariharan" .. Replace first "H" with "A" SQL
I have one scenario where I want replace only first "H" character among others "H" positions and remaining keep as it is.

There are many simplistic answers for this on Stack Overflow that don't take into account the case where the character being searched for doesn't exist in the string. In these cases, the SQL will return NULL if the replacement character does not exist in the string. Try this instead:
declare #name varchar(max), #ToReplace varchar(max), #ReplaceWith varchar(max)
set #name = 'Vishal Hariharan'
set #ToReplace = 'H'
set #ReplaceWith = 'A'
select #name
select stuff(#name, charindex(#ToReplace,#name),1, CASE WHEN charindex(#ToReplace,#name) <> 0 THEN #ReplaceWith ELSE #ToReplace END)
The CASE statement simply checks if the character exists in the string, and if it doesn't, it replaces the matching character with itself.

DECLARE #findChar varchar(max)='H'
DECLARE #RepalceCharacter varchar(max)='A'
DECLARE #OriginText varchar(max)='Vishal Hariharan'
IF (CharIndex(#findChar, #OriginText)<>0)
SELECT Stuff(#OriginText, CharIndex(#findChar, #OriginText), Len(#findChar), #RepalceCharacter)
ELSE
SELECT #OriginText

Related

Regex in LIKE Clause that accepts only Alphanumeric and dashes

Below is my SQL function script that will help identify the alphanumeric value and dashes (-):
CREATE FUNCTION [dbo].[FN_VALIDATE_ALPHANUMERIC_AND_DASHES](#TX_INPUT VARCHAR(1000))RETURNS BIT AS
BEGIN
DECLARE #bitInputVal AS BIT = 0
DECLARE #InputText VARCHAR(1000)
SET #InputText = LTRIM(RTRIM(ISNULL(#TX_INPUT,'')))
IF #InputText <> ''
BEGIN
SET #bitInputVal = CASE
WHEN #InputText LIKE '%[A-Za-z0-9-]%' THEN 1
ELSE 0
END
END
RETURN #bitInputVal
END
I have problem which I try this query:
SELECT dbo.FN_VALIDATE_CLAIMANT_REF_NO('AbcdefgH-1234*') it gives me a result of 1 though the character * is not included in the regex and should return 0 instead.
What I want to achieve is to explicitly verify if the string consist of alphanumeric (alphabets and numbers) and dashes only.
Please note that there are no limitation in length of the characters, only check if the string consist of alphanumeric and dashes.
You are testing for "whether any alphabet, number or dash is present in the string"
You should instead test whether any character other than alphabet, number or dash is present.
SET #bitInputVal = CASE WHEN #InputText LIKE '%[^A-Za-z0-9-]%' THEN 0 ELSE 1 END

sql Return string between two characters

I want to know a flexible way to extract the string between two '-'. The issue is that '-' may or may not exist in the source string. I have the following code which works fine when '-' exists twice in the source string, marking the start and end of the extracted string. But it throws an error "Invalid length parameter passed to the LEFT or SUBSTRING function" when there is only one '-' or none at all or if the string is blank. Can someone please help? Thanks
declare #string varchar(100) = 'BLAH90-ExtractThis-WOW'
SELECT SUBSTRING(#string,CHARINDEX('-',#string)+1, CHARINDEX('-',#string,CHARINDEX('-',#string)+1) -CHARINDEX('-',#string)-1) as My_String
Desired Output: ExtractThis
If there is one dash only e.g. 'BLAH90-ExtractThisWOW' then the output should be everything after the first dash i.e. ExtractThisWOW. If there are no dashes then the string will have a blank space instead e.g. 'BLAH90 ExtractThisWOW' and should return everything after the blank space i.e. ExtractThisWOW.
You can try something like this.
When there is no dash, it starts at the space if there is one or take the whole string if not.
Then I look if there is only one dash or 2
declare #string varchar(100) = 'BLAH90-ExtractThis-WOW'
declare #dash_pos integer = CHARINDEX('-',#string)
SELECT CASE
WHEN #dash_pos = 0 THEN
RIGHT(#string,LEN(#string)-CHARINDEX(' ',#string))
ELSE (
CASE
WHEN #dash_pos = LEN(#string)-CHARINDEX('-',REVERSE(#string))+1
THEN RIGHT(#string,LEN(#string)-#dash_pos)
ELSE SUBSTRING(#string,#dash_pos+1, CHARINDEX('-',#string,#dash_pos+1) -
#dash_pos -1)
END
)
END as My_String
Try this. If there are two dashes, it'll take what is inside. If there is only one or none, it'll keep the original string.
declare #string varchar(100) = 'BLAH-90ExtractThisWOW'
declare #dash_index1 int = case when #string like '%-%' then CHARINDEX('-', #string) else -1 end
declare #dash_index2 int = case when #string like '%-%'then len(#string) - CHARINDEX('-', reverse(#string)) + 1 else -1 end
SELECT case
when #dash_index1 <> #dash_index2 then SUBSTRING(#string,CHARINDEX('-',#string)+1, CHARINDEX('-',#string,CHARINDEX('-',#string)+1) -CHARINDEX('-',#string)-1)
else #string end
as My_String
Take your existing code:
declare #string varchar(100) = 'BLAH90-ExtractThis-WOW'
SELECT SUBSTRING(#string,CHARINDEX('-',#string)+1, CHARINDEX('-',#string,CHARINDEX('-',#string)+1) -CHARINDEX('-',#string)-1) as My_String
insert one line, like so:
declare #string varchar(100) = 'BLAH90-ExtractThis-WOW'
SET #string = #string + '--'
SELECT SUBSTRING(#string,CHARINDEX('-',#string)+1, CHARINDEX('-',#string,CHARINDEX('-',#string)+1) -CHARINDEX('-',#string)-1) as My_String
and you're done. (If NULL, you will get NULL returned. Also, this will return all data based on the FIRST dash found in the string, regardless of however many dashes are in the string.)

Replace every alpha character with itself + wildcard in string SQL Server

My goal is to create a query that will search for results related to a specific keyword.
Say in a database we had the word cat.
Regardless of if the user types C a t, C.A.T. or Cat I want to find a result related to the search as long as the alpha numeric characters are in the correct sequence that is all that matters
Say in the database we have these 4 records
cat
c/a/t
c.a.t
c. at
If the user types in C#$*(&A T I'd like to get all 4 results.
What I have written so far in my query is a function that strips any non-alphanumeric characters from the input string.
What can I do to replace each alphanumeric character with itself and add a wildcard at the end?
For every alpha character my input would look similar to this
C%[^a-zA-Z0-9]%A%[^a-zA-Z0-9]%T%[^a-zA-Z0-9]%
Actually, that search string will return only one record from this table: the row with 'c.a.t '.
This is because the expression C%[^a-zA-Z0-9]%A does not mean there can't be any alpha-numeric chars between C and A.
What it actually means is there should be at least one non alpha-numeric value between C and A.
Moreover, it will return incorrect values as well - a value like 'c u a s e t ' will be returned.
You need to change your where clause to something like this:
WHERE column LIKE '%C%A%T%'
AND column NOT LIKE '%C%[a-zA-Z0-9]%A%[a-zA-Z0-9]%T%'
This way, if you have cat in the correct order, the first row will resolve to true, and if there are no other alpha-numeric chars between c, a, and t the second row will resolve to true.
Here is a test script, where you can see for yourself what I mean:
DECLARE #T AS TABLE
(
a varchar(20)
)
INSERT INTO #T VALUES
('cat'),
('c/a/t'),
('c.a.t '),
('c. at'),
('c u a s e t ')
-- Incorrect where clause
SELECT *
FROM #T
WHERE a LIKE 'C%[^a-zA-Z0-9]%A%[^a-zA-Z0-9]%T%[^a-zA-Z0-9]%'
-- correct where clause
SELECT *
FROM #T
WHERE a LIKE '%C%A%T%'
AND a NOT LIKE '%C%[a-zA-Z0-9]%A%[a-zA-Z0-9]%T%'
You can also see it in action in this link.
And since I had some spare time, here is a script to create both the like and the not like patterns from the input string:
DECLARE #INPUT varchar(100) = '#*# c %^&# a ^&*$&* t (*&(%!##$'
DECLARE #Index int = 1,
#CurrentChar char(1),
#Like varchar(100),
#NotLike varchar(100) = '%'
WHILE #Index < LEN(#Input)
BEGIN
SET #CurrentChar = SUBSTRING(#INPUT, #Index, 1)
IF PATINDEX('%[^a-zA-Z0-9]%', #CurrentChar) = 0
BEGIN
SET #NotLike = #NotLike + #CurrentChar + '%[a-zA-Z0-9]%'
END
SET #Index = #Index + 1
END
SELECT #NotLike = LEFT(#NotLike, LEN(#NotLike) - 12),
#Like = REPLACE(#NotLike, '%[a-zA-Z0-9]%', '%')
SELECT *
FROM #T
WHERE a LIKE #Like
AND a NOT LIKE #NotLike
You can recursively go through your (cleaned) search string and to each letter add the expression you would like. In my example #builtString should be what you would like to use further on, if I understood correctly.
declare #cleanSearch as nvarchar(10) = 'CAT'
declare #builtString as nvarchar(100) = ''
WHILE LEN(#cleanSearch) > 0 -- loop until you deplete the search string
BEGIN
SET #builtString = #builtString + substring(#cleanSearch,1,1) + '%[^a-zA-Z0-9]%' -- append the letter plus regular expression
SET #cleanSearch = right(#cleanSearch, len(#cleanSearch) - 1) -- remove first letter of the search string
END
SELECT #builtString --will look like C%[^a-zA-Z0-9]%A%[^a-zA-Z0-9]%T%[^a-zA-Z0-9]%
SELECT #cleanSearch --#cleanSearch is now empty

Trim Special Char from SQL String

I am using SQL Server 2008
I have sql string in column with ; separated values. How i can trim the below value
Current string:
;145615;1676288;178829;
Output:
145615;1676288;178829;
Please help with sql query to trim the first ; from string
Note : The first char may be or may not be ; but if it is ; then only it should trim.
Edit: What i had tried before, although it doesn't make sense after so many good responses.
DECLARE
#VAL VARCHAR(1000)
BEGIN
SET #VAL =';13342762;1334273;'
IF(CHARINDEX(';',#VAL,1)=1)
BEGIN
SELECT SUBSTRING(#VAL,2,LEN(#VAL))
END
ELSE
BEGIN
SELECT #VAL
END
END
SELECT CASE WHEN col LIKE ';%'
THEN STUFF(col,1,1,'') ELSE col END
FROM dbo.table;
Just check the first character, and if it matches, start from the second character:
SELECT CASE WHEN SUBSTRING(col,1,1) = ';'
THEN SUBSTRING(col,2,LEN(col))
ELSE col
END AS col
Here's an example:
DECLARE #v varchar(10)
SET #v = ';1234'
SELECT
CASE
WHEN LEFT(#v,1) = ';' THEN RIGHT(#v, LEN(#v) - 1)
ELSE #v
END
A further development on #Aaron Bertrand's answer:
SELECT
STUFF(col, 1, PATINDEX(';%', col), '')
FROM ...
PATINDEX is similar to LIKE in that it uses a pattern search, but being a function it also returns the position of the first match. In this case, since we a looking for a ; specifically at the beginning of a string, the position returned is going to be either 1 (if found) or 0 (if not found). If it is 1, the STUFF function will delete 1 character at the beginning of the string, and if the position is 0, STUFF will delete 0 characters.

Split string on only first occurance of character/delimiter

I've been searching all morning for this.
My knowledge of SQL Server is not excellent, and I'm out of answers.
Concrete examples are: City-Of-Style or Part1-Part2.
I need to split these examples into City and Of-Style and Part1 and Part2.
I figured out this little piece of code, but it switches part1 and part2 if the string contains a '-'.
PARSENAME(REPLACE('sample-string', '-', '.'), 1))
Any help on accomplishing this (preferably without a 200 lines function) is greatly appreciated.
If I understand correctly this will do the job; Click here for the fiddle
DECLARE #s VARCHAR(50)= 'City-Of-Style'
SELECT SUBSTRING(#s,0,CHARINDEX('-',#s,0)) AS firstPart,
SUBSTRING(#s,CHARINDEX('-',#s,0)+1,LEN(#s)) AS secondPart
If there are no dashes in the string, you get a blank. The below snippet gives you the first part if there's a dash, otherwise the whole string.
DECLARE #TextIn VARCHAR(50)= 'City-Of-Style'
DECLARE #TextOut VARCHAR(500)
SELECT CASE WHEN CHARINDEX('-',#TextIn)>0 THEN SUBSTRING(#TextIn,0,CHARINDEX('-',#TextIn,0)) ELSE #TextIn END
In SQL, you can use the split_part function.
E.g. cast(split_part(column,'-',1) as text) as new_column
Input: king-adfad-adfadd
Output: king
Building on the previous answers, I offer this as a solution - which provides both the first and last elements. If their is no delimiter found, the last element is empty.
DECLARE
#del varchar(1) = '-',
#TextIn nvarchar(20) = 'City-Of-Style'
SELECT CASE WHEN CHARINDEX(#del,#TextIn)>0 THEN SUBSTRING(#TextIn,0,CHARINDEX(#del,#TextIn,0)) ELSE #TextIn END AS firstPart,
CASE WHEN CHARINDEX(#del,#TextIn)>0 THEN SUBSTRING(#TextIn,CHARINDEX(#del,#TextIn,0)+1,LEN(#TextIn)) ELSE '' END AS secondPart
Or, if you're working in a stored procedure, you could assign the results to variables:
DECLARE
#del nvarchar(1) = '-',
#firstPart nvarchar(100),
#lastPart nvarchar(100),
#TextIn nvarchar(20) = 'City-Of-Style'
SELECT #firstPart = (CASE WHEN CHARINDEX(#del,#TextIn)>0 THEN SUBSTRING(#TextIn,0,CHARINDEX(#del,#TextIn,0)) ELSE #TextIn END),
#lastPart = (CASE WHEN CHARINDEX(#del,#TextIn)>0 THEN SUBSTRING(#TextIn,CHARINDEX(#del,#TextIn,0)+1,LEN(#TextIn)) ELSE '' END)
select #firstPart, #lastPart