Find a string inside a string and update in SQL Server - sql

I have a table like this :
create table Fbank (id int, COCODE nvarchar(max))
insert into Fbank
values (1, '<row xml:space="preserve" id="174580000041250.040002">
<c1>HTG115960001</c1>
<c2>14013514,48</c2>
<c3>222</c3>
<c4>BAL MIGRATED</c4>
<c5>NULL</c5>
<c6>NULL</c6>
<c7>NULL</c7>
<c8>9900</c8>
<c9>11596</c9>
<c10>20151017</c10>
<c11>HTG</c11>
<c12>NULL</c12>
<c13>NULL</c13>
<c14>FT1529010083</c14>
<c15>1</c15>
<c16>FT1529010083</c16>
<c17>FT</c17>
<c18>20151017</c18>
<c19>NULL</c19>
<c20>0</c20>
<c21>5033_INPUTTER__OFS_AUTO.FT</c21>
<c22>5033_INPUTTER_OFS_AUTO.FT</c22>
<c23>1510181127</c23>
<c24>HG0010001</c24>
</row>')
I need to replace the string inside the tag c24 tag..
Excepted output: I need to replace the letter 'G' to be replaced with 'T' like this inside c24 tag - HT0010001 and all the rest should be same unchanged...
What I tired:
declare #searchText varchar(20) = (
select SUBSTRING(COCODE,CHARINDEX('<c24>', COCODE), 7)
from FBNK_EB_SFF_ACCT_HI000)
update Fbank
set cocode = STUFF(#searchText, CHARINDEX('<c24>', COCODE), 1, 'T')

If the code always begins with 'H', then I imagine it's easier to just have '<c24>H' be part of the string to replace, but then add it back again:
update Fbank
set COCODE = replace(cocode, '<c24>HG', '<c24>HT');
If it doesn't, then I'd say you're on the right track with charindex and substring. But use patindex instead, and update fbank directly, don't put the search term into any variable. If you're trying to split up your logic into parts, consider cross apply:
update fb
set cocode = stuff(cocode, ix, 1, 'T')
from Fbank fb
cross apply (select ix = patindex('%<c24>%', cocode) + 6) ap
where substring(cocode, ix, 1) = 'G'

Related

Handling variables in SQL Server

I have a procedure that needs to handle up to 60 different variables.
The variables have a standardized naming convention.
#TextParameter1 varchar(443) = NULL,
#TextParameter2 varchar(443) = NULL,
#TextParameter3 varchar(443) = NULL
I need to be able to check which variables are NULL and which aren't, and then handle the values of the non-null variables.
I tried using dynamic SQL to iterate over the variables by making the first portion of the variable name a string and iterating through the numbers on the end.
declare #rownum int = 1
while #rownum <= 60
declare #var_sql nvarchar(max) = 'INSERT INTO #slicer
SELECT IDENTITY(Int, 1, 1) AS rowkey, value
FROM STRING_SPLIT(CAST(#DetailQueryTextParameter' + CAST(#rownum AS nvarchar(3)) AS varchar(4000)), '^')'
execute #var_sql
Set #rownum = #rownum + 1
This will return an error claiming that #DetailQueryTextParameter needs to be declared first. What is the best way to handle all of these variables? I could do by writing a line of code for every single variable, but it seems like there is a better way. Can I insert the variable names into a table and iterate from there?
(The below was updated to include the SPLIT_STRING().)
You can use a VALUES subselect (not sure if that is the proper term) to combine all of your parameters into a single collection. You can then filter out the null values and pass the remaining values into STRING_SPLIT() using a CROSS APPLY.
DECLARE
#TextParameter1 varchar(443) = NULL,
#TextParameter2 varchar(443) = 'aaa^bbb',
#TextParameter3 varchar(443) = NULL,
#TextParameter4 varchar(443) = 'xxx^yyy^zzz',
#TextParameter5 varchar(443) = NULL
SELECT A.*, B.Value AS SplitValue
FROM (
VALUES
(1, #TextParameter1),
(2, #TextParameter2),
(3, #TextParameter3),
(4, #TextParameter4),
(5, #TextParameter5)
) A(Parameter, Value)
CROSS APPLY STRING_SPLIT(A.Value, '^') B
WHERE A.Value IS NOT NULL
Which would yield results like:
Parameter
Value
SplitValue
2
aaa^bbb
aaa
2
aaa^bbb
bbb
4
xxx^yyy^zzz
xxx
4
xxx^yyy^zzz
yyy
4
xxx^yyy^zzz
zzz
See this db<>fiddle.

Replace the multiple values between 2 characters in azure sql

In Azure SQL, I'm attempting to delete any text that is present between the < and > characters to my column in my table
Sample text:
The best part is that. < br >Note:< br >< u> reading
:< /u> < span style="font-family: calibri,sans-serif; font-size: 11pt;"> moral stories from an early age
< b>not only helps your child.< /b>< br>< u>in
learning important: < /u>< /span>< span style="font-family: calibri;
">life lessons but it also helps, in language development.< /span>< ./span>
Output:
The best part is that. reading: moral stories from an early age not only helps your child in learning important: life lessons but it also helps in language development.
I tried below query its working only for small comments text:
SELECT [Comments],REPLACE([Comments], SUBSTRING([Comments], CHARINDEX('<', [Comments]), CHARINDEX('>', [Comments]) - CHARINDEX('<', [Comments]) + 1),'') AS result
FROM table
I have taken input table named check_1 and sample data is inserted into that table.
This query removes only the first occurring pattern.
SELECT [Comments],REPLACE([Comments], SUBSTRING([Comments], CHARINDEX('<', [Comments]), CHARINDEX('>', [Comments]) - CHARINDEX('<', [Comments]) + 1),'') AS result
FROM check_1
In order to remove all string patterns beginning with '<' and ending with '>' in the text, a user defined function with a while loop is created.
CREATE FUNCTION [dbo].[udf_removetags] (#input_text VARCHAR(MAX)) RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE #pos_1 INT
DECLARE #pos_n INT
DECLARE #Length INT
SET #pos_1 = CHARINDEX('<',#input_text)
SET #pos_n = CHARINDEX('>',#input_text,CHARINDEX('<',#input_text))
SET #Length = (#pos_n - #pos_1) + 1
WHILE #pos_1 > 0 AND #pos_n > 0 AND #Length > 0
BEGIN
SET #input_text = replace(#input_text,substring(#input_text,#pos_1,#Length),'')
SET #pos_1 = CHARINDEX('<',#input_text)
SET #pos_n = CHARINDEX('>',#input_text,CHARINDEX('<',#input_text))
SET #Length = (#pos_n - #pos_1) + 1
END
RETURN #input_text
END
select [dbo].[udf_removetags](comments) as result from check_1
Output String:
The best part is that. Note: reading : moral stories from an early age not only helps your child.in learning important: life lessons but it also helps, in language development.
You can also use Stuff [Refer Microsoft document on STUFF] in place of replace+substring function.
Replace this SET #input_text = replace(#input_text,substring(#input_text,#pos_1,#Length),'')
line with the line
SET #input_text = STUFF(#input_text,#pos_1,#Length,'')
in the user defined function.
Result will be same.
According to https://learn.microsoft.com/../azure/../regexp_replace Azure supports REGEXP_REPLACE.
This means it should be possible to replace all '<...>' by '' via
select regexp_replace(comments, '<[^>]*>', '') from mytable;

Error Handling for numbers of delimiters when extracting substrings

Situation: I have a column where each cell can have up to 5 delimiters. However, it's possible that there are none.
Objective: How do i handle errors such as :
Invalid length parameter passed to the LEFT or SUBSTRING function.
in the case that it cannot find the specified delimiter.
Query:
declare #text VARCHAR(111) = 'abc-def-geeee-ifjf-zzz'
declare #start1 as int
declare #start2 as int
declare #start3 as int
declare #start4 as int
declare #start_index_reverse as int
set #start1 = CHARINDEX('-',#text,1)
set #start2 = CHARINDEX('-',#text,charindex('-',#text,1)+1)
set #start3 = CHARINDEX('-',#text,charindex('-',#text,CHARINDEX('-',#text,1)+1)+1)
set #start4 = CHARINDEX('-',#text,charindex('-',#text,CHARINDEX('-',#text,CHARINDEX('-',#text,1)+1)+1)+1)
set #start_index_reverse = CHARINDEX('-',REVERSE(#text),1)
select
LEFT(#text,#start1-1) AS Frst,
SUBSTRING(#text,#start1+1,#start2-#start1-1) AS Scnd,
SUBSTRING(#text,#start2+1,#start3-#start2-1) AS Third,
SUBSTRING(#text,#start3+1,#start4-#start3-1)AS Third,
RIGHT(#text,#start_index_reverse-1) AS Lst
In this case my variable includes 5 delimiters and so my query works but if i removed one '-' it would break.
XML support in SQL Server brings about some unintentional but useful tricks. Converting this string to XML allows for some parsing that is far less messy than native string handling, which is very far from awesome.
DECLARE #test varchar(111) = 'abc-def-ghi-jkl-mnop'; -- try also with 'abc-def'
;WITH n(x) AS
(
SELECT CONVERT(xml, '<x>' + REPLACE(#test, '-', '</x><x>') + '</x>')
)
SELECT
Frst = x.value('/x[1]','varchar(111)'),
Scnd = x.value('/x[2]','varchar(111)'),
Thrd = x.value('/x[3]','varchar(111)'),
Frth = x.value('/x[4]','varchar(111)'),
Ffth = x.value('/x[5]','varchar(111)')
FROM n;
For a table it's almost identical:
DECLARE #foo TABLE ( col varchar(111) );
INSERT #foo(col) VALUES('abc-def-ghi-jkl-mnop'),('abc'),('def-ghi');
;WITH n(x) AS
(
SELECT CONVERT(xml, '<x>' + REPLACE(col, '-', '</x><x>') + '</x>')
FROM #foo
)
SELECT
Frst = x.value('/x[1]','varchar(111)'),
Scnd = x.value('/x[2]','varchar(111)'),
Thrd = x.value('/x[3]','varchar(111)'),
Frth = x.value('/x[4]','varchar(111)'),
Ffth = x.value('/x[5]','varchar(111)')
FROM n;
Results (sorry about the massive size, seems this doesn't handle 144dpi well):
add a test before your last select
then you should decide how to handle the other case (when one of start is 0)
You can also refer to this link about splitting a string in sql server
which is uses a loop and can handle any number of delimiters
if #start1>0 and #start2>0 and #start3>0 and #start4>0
select LEFT(#text,#start1-1) AS Frst,
SUBSTRING(#text,#start1+1,#start2-#start1-1) AS Scnd,
SUBSTRING(#text,#start2+1,#start3-#start2-1) AS Third,
SUBSTRING(#text,#start3+1,#start4-#start3-1)AS Third,
RIGHT(#text,#start_index_reverse-1) AS Lst

How to split a string in sql server using stored procedure and insert the data to table

<pre>update d
set d.Price = null
from dbo.SalDocumentDetail d
left join dbo.StkWarehouse w on w.WarehouseID = d.WarehouseID
where DocumentID=" + 1 + "
and DocumentTypeID=" + 2 + "
and FiscalYear= " + 2016 + "
and isnull(isPrescription,0) <>1
and w.POSType is null
and ProductName BETWEEN ''C' 'AND' 'M''
and Country LIKE ''%land%'''</pre>
Actually this string is only a sample one my original string is very large . i am not getting a point that if i break this string than how many variables i have to make to capture the data also after splitting the string i want that to be inserted into data table containing columns as Felid and Value?
I want my result like :
<pre>
Felid Value
DocumentID= 1
DocumentTypeID= 2
FiscalYear= 2016
isnull(isPrescription,0) <>= 1
w.POSType is= null
ProductName= C
ProductName= M
Country= land
</pre>
<pre>I Use this function but this function split 'and' not split like what i want in my result i want split 'and,or,like,is,between ' if function find any this split it to two columns (Felid and Value)</pre>
<pre>ALTER FUNCTION [dbo].[fnSplitString]
(#List NVARCHAR(MAX),#Delimiter NVARCHAR(255))
RETURNS #Items TABLE(Felid NVARCHAR(Max),Valu nvarchar(MAx))
WITH SCHEMABINDING
AS BEGIN
DECLARE #ll INT=LEN(#List)+1,#ld INT=LEN(#Delimiter);
WITH a AS
(SELECT
[end]=COALESCE(NULLIF(CHARINDEX(#Delimiter,#List,1),0),#ll),
[VlaueFelid]=SUBSTRING(#List,(select
CHARINDEX('where',#List)+5),COALESCE(NULLIF(CHARINDEX('=', #List,0),0),#ll) ) ,
[Value]=SUBSTRING(#List,(select CHARINDEX('="',#List)+2),(select CHARINDEX('and',#List))-(select C`enter code here`HARINDEX('="',#List)+3))
UNION ALL
SELECT
[end]=COALESCE(NULLIF(CHARINDEX(#Delimiter,#List,[end]+#ld), 0),#ll),
[VlaueFelid]=SUBSTRING(#List,[end]+#ld, COALESCE(NULLIF(CHARINDEX('=',#List, [end]+#ld),0),#ll)-[end]-#ld),
[Value]=SUBSTRING(#List,[end]+#ld+16, COALESCE(NULLIF(CHARINDEX('=',#List,[end]+#ld),0),#ll)-[end]-#ld-5)
FROM a WHERE [end]< #ll) INSERT #Items SELECT[VlaueFelid],[Value] FROM a WHERE LEN([VlaueFelid])>0 RETURN;
END</pre>

MS-SQL - Extracting numerical portion of a string

I have an MS-SQL table, with a column titled 'ImportCount'.
Data in this column follows the below format:
ImportCount
[Schedules] 1376 schedule items imported from location H:\FOLDERA\AA\XX...
[Schedules] 10201 schedule items imported from location H:\FOLDERZZ\PERS\YY...
[Schedules] 999 schedule items imported from location R:\PERS\FOLDERA\AA\XX...
[Schedules] 21 schedule items imported from location H:\FOLDERA\MM\2014ZZ...
What I would like to do is extract that numerical portion of the data (which varies in length), but am struggling to get the right result. Would appreciate any help on this!
Thanks.
Try
select left(ImportCount, patindex('%[^0-9]%', ImportCount+'.') - 1)
select SUBSTRING(ImportCount,13,patindex('% schedule items%',ImportCount)-13) from table name
Try this..You can declare it as a SQL function also.
DECLARE #intText INT
DECLARE #textAplhaNumeric varchar(100)
set #textAplhaNumeric = '1376 schedule items imported from location'
SET #intText = PATINDEX('%[^0-9]%', #textAplhaNumeric)
BEGIN
WHILE #intText > 0
BEGIN
SET #textAplhaNumeric = STUFF(#textAplhaNumeric, #intText, 1, '' )
SET #intText = PATINDEX('%[^0-9]%', #textAplhaNumeric)
END
END
Select #textAplhaNumeric //output is 1376
It will work in case of NULL or empty values.
Please try:
SELECT LEFT(Val,PATINDEX('%[^0-9]%', Val+'a')-1) from(
SELECT
STUFF(ImportCount, 1, PATINDEX('%[0-9]%', ImportCount)-1, '') Val
FROM YourTable
)x