Replacing a string before the last "\" character in SQL query - sql-server

Query:
SELECT filePath FROM Table WHERE filePath IS NOT NULL
It'll return something like \\server\folder1\folder2\filename.tif
I need to query it to replace "\\server\folder1\folder2\" with a variable that's in the stored procedure (#Path) and end the format of the file like .jpg.
So the result would be something like #Path + '.jpg'
How would I go about doing this?

You can use a combination of string functions like REVERSE, SUBSTRING, LEFT and CHARINDEX:
CREATE TABLE YourTable(filePath VARCHAR(2000))
INSERT INTO YourTable VALUES('\\server\folder1\folder2\filename.tif');
DECLARE #path VARCHAR(2000) = 'path\to\folder\'
SELECT
[File] = REVERSE(LEFT(REVERSE(filePath), CHARINDEX('\', REVERSE(filePath),0) - 1)),
[File without ext] =
SUBSTRING(
REVERSE(LEFT(REVERSE(filePath), CHARINDEX('\', REVERSE(filePath), 0) - 1)),
0,
CHARINDEX(
'.',
REVERSE(LEFT(REVERSE(filePath), CHARINDEX('\', REVERSE(filePath), 0) - 1)),
0
)
),
[Final String] =
#path +
SUBSTRING(
REVERSE(LEFT(REVERSE(filePath), CHARINDEX('\', REVERSE(filePath), 0) - 1)),
0,
CHARINDEX(
'.',
REVERSE(LEFT(REVERSE(filePath), CHARINDEX('\', REVERSE(filePath), 0) - 1)),
0
)
) +
'.jpg'
FROM YourTable

Use a combination of REVERSE and CHARINDEX to locate the last \:
DECLARE #filePath VARCHAR(500) = '\\server\folder1\folder2\filename.tif'
DECLARE #newPath VARCHAR(500) = '\\server2\newpath\'
SELECT #newPath +
SUBSTRING(#filePath, LEN(#filePath) - CHARINDEX('\', REVERSE(#filePath))+2, LEN(#filePath))

Related

Extract text in string from column

How can I return column pathToFolder but only containing the letters hello3\heeello4?
create table #testing(pathToFolder varchar(200) )
insert into #testing values
('c:\hello\hello2\hello3\heeello4\hello5'),
('c:\hi\hi2\hi3\hiii4\hi5')
select pathToFolder from #testing;
I need to return hello3\heeello4 and hi3\hiii4 in the select statement.
Try this:
declare #count int = 0,
#position1 int = 0,
#position2 int = 0,
#string1 varchar(50) = 'c:\hello\hello2\hello3\heeello4\hello5',
#string2 varchar(50) = 'c:\hi\hi2\hi3\hiii4\hi5'
while (#count < 4)
begin
set #position1 = cast( CHARINDEX('\', #string1, #position1) as int) + 1
set #position2 = cast( CHARINDEX('\', #string2, #position2) as int) + 1
set #count = #count + 1
end
set #string1 = (select right(#string1, #position1 -2))
set #string2 = (select right(#string2, #position2 -2))
while (#count < 7)
begin
set #position1 = cast( CHARINDEX('\', #string1, #position1) as int) + 1
set #position2 = cast( CHARINDEX('\', #string2, #position2) as int) + 1
set #count = #count + 1
end
set #string1 = (select left(#string1, #position1 -2))
set #string2 = (select left(#string2, #position2 -2))
select #string1, #string2
The question has finally been edited down to a classic "I have"/"I need" with no indication of how the minimal sample data relates to the desired result. What it does offer is, at best, misleading: "but only containing the letters hello3\heeello4".
So it goes. The following code does stuff that might be the stuff that is wanted. It also meets the reclusive "i need to use it on a column in a select statement" requirement. There is, as of this time, no requirement that it not burst into flames if the path doesn't contain enough directories.
with HelpVampire as (
select Path,
CharIndex( '\', Path ) as ReverseSolidus1Position,
CharIndex( '\', Path, CharIndex( '\', Path ) + 1 ) as ReverseSolidus2Position,
CharIndex( '\', Path, CharIndex( '\', Path, CharIndex( '\', Path ) + 1 ) + 1 ) as ReverseSolidus3Position,
Substring( Path, CharIndex( '\', Path, CharIndex( '\', Path, CharIndex( '\', Path ) + 1 ) + 1 ) + 1, 255 ) as Remainder
from ( values
( 'c:\hello\hello2\hello3\heeello4\hello5' ), ( 'c:\hi\hi2\hi3\hiii4\hi5' )
) as Samples ( Path ) )
select *,
CharIndex( '\', Remainder ) as PerverseSolidus1Position,
Substring( Remainder, CharIndex( '\', Remainder ) + 1, 255 ) as ASubstringFromThePath
from HelpVampire;

How to Include single quote in the STUFF

I have my sql query as follows which is giving the result by Capitalizing the given strings but I need the with single quote on each of the individual one how can I do that
DECLARE #Xml XML
DECLARE #Propercase VARCHAR(max)
DECLARE #delimiter VARCHAR(5)
SET #delimiter=' '
DECLARE #string nvarchar(max)='ABC,DEF,GHI,JKL'
SET #Xml = Cast(( '<String>'
+ #string+ '</String>' ) AS XML)
;WITH cte
AS (SELECT a.value('.', 'varchar(max)') AS strings
FROM #Xml.nodes('String') AS FN(a))
-- SELECT * FROM cte;
SELECT #ProperCase = Stuff((SELECT ' ' +'('+ + Upper(LEFT(strings, 1))
+ Upper(Substring(strings, 2, Len(strings)) + ')'
)
FROM cte
FOR xml path('')), 1, 1, '')
SELECT #ProperCase
Currently my output is as follows (ABC,DEF,GHI,JKL) I need this to be ('ABC','DEF','GHI','JKL')
DECLARE #Xml XML
DECLARE #Propercase VARCHAR(max)
DECLARE #delimiter VARCHAR(5)
SET #delimiter=' '
DECLARE #string nvarchar(max)='ABC,DEF,GHI,JKL'
SET #Xml = Cast(( '<String>'
+ #string+ '</String>' ) AS XML)
;WITH cte
AS (SELECT a.value('.', 'varchar(max)') AS strings
FROM #Xml.nodes('String') AS FN(a))
SELECT #ProperCase = '(' + REPLACE(STUFF((SELECT ','''+ Upper(LEFT(strings, 1))
+ Upper(Substring(strings, 2, Len(strings))) + ''')'
FROM cte
FOR xml path('')), 1, 1, ''),',',''',''')
SELECT #ProperCase
Note that all the STUFF really does is drop the leading comma
Double up the single quotes to be output as one single quote character while still being wrapped in single quotes. So four (4) single quotes will output a single quote as a String.
DECLARE #prelimiter VARCHAR(5)
DECLARE #delimiter VARCHAR(5)
SET #prelimiter = '''' --## Ouptuts single quote
SET #delimiter = ''', ''' --## Ouptuts single quote then comma then space then single quote
SELECT
STUFF(' ', 1, 1,
'(' + #prelimiter + 'ABC' + #delimiter + 'DEF' + #delimiter + 'GHI' + ''')'
) AS Example
Output: ('ABC', 'DEF', 'GHI')

Replace multiple special character to single dash

Hi I Have my data as (SCARF.) / (WRAPS) and I want to show it as SCARF-WRAPS but I am not able to get it
My below code is as
DECLARE #str VARCHAR(400)
DECLARE #specialchars VARCHAR(50) = '%[/,~,#,#,$,%,&,*,(,),.,!^?:]%'
--SET #str = 'KRA!NTHI##KUMAR, KU%^?MAR GO~()$U.BigGrin'
SET #str = '(SCARF.) / (WRAPS)'
SET #str = REPLACE(#str,'.','')
WHILE PATINDEX( #specialchars, #str ) > 0
SET #str = REPLACE(REPLACE( #str, SUBSTRING( #str, PATINDEX( #specialchars, #str ), 1 ),'-'),'-','-')
IF(LEFT(#str, 1) = '-')
set #str = RIGHT(#str, LEN(#str) - 1)
IF(RIGHT(#str, 1) = '-')
set #str = LEFT(#str, LEN(#str) - 1)
SELECT REPLACE(#str,' ','-')
but it is giving data as SCARF-----WRAPS instead of SCARF-WRAPS
I have such type of data as multiple and I want to convert them as with single dash.
For example:
'SKIN CARE & BEAUTY SUPPLY' should change to 'SKIN-CARE-BEAUTY-SUPPLY'
'BANDANAS / DURAGS / WRAPS' should change to 'BANDANAS-DURAGS-WRAPS'
'HATS & MUFFLERS' should change to 'HATS-MUFFLERS'
Try this:
DECLARE #str VARCHAR(400)='(SCARF.) / (WRAPS)'
DECLARE #specialchars VARCHAR(50) = '%[/,~,#,#,$,%,&,*,(,),.,!^?:-]%'
WHILE PATINDEX( #specialchars, #str ) > 0
SET #str = REPLACE( #str, SUBSTRING( #str, PATINDEX( #specialchars, #str ), 1 ),' ')
SELECT REPLACE(REPLACE(REPLACE(RTRIM(LTRIM(#str)), ' ', '- '), ' -', ''), ' ', '')
I'm not going to say this solution is pretty; it's not. it does the job but I don't expect it to work fast. It makes use of Alan Burstein's NGrams8k, so you'll need to ensure you have a copy on your server as well.
if you don't understand it, feel free to ask (apart from how NGrams8K works, that's what the article is for):
CREATE TABLE T (string varchar(400));
INSERT INTO T
VALUES ('KRA!NTHI##KUMAR, KU%^?MAR GO~()$U.BigGrin'),
('(SCARF.) / (WRAPS)');
GO
WITH Replacements AS (
SELECT *,
CASE WHEN NG.token NOT LIKE '[ /,~##$%&*().!^?:]' THEN NG.token ELSE '-' END AS TokenR
FROM T
CROSS APPLY dbo.NGrams8k ('-'+T.String+'-',1) NG),
Repeating AS (
SELECT *,
CASE WHEN TokenR = '-' AND TokenR = LAG(TokenR) OVER (PARTITION BY string ORDER BY position) THEN NULL ELSE TokenR END AS TokenRR
FROM Replacements),
Cleaned AS (
SELECT string,
STUFF((SELECT sq.TokenRR + ''
FROM Repeating sq
WHERE sq.TokenRR IS NOT NULL
AND sq.string = R.string
ORDER BY position
FOR XML PATH('')),1,1,'') AS CleanString
FROM Repeating R
GROUP BY string)
SELECT string, LEFT(CleanString, LEN(CleanString)-1) AS CleanedString
FROM Cleaned;
GO
DROP TABLE T;
With the sample data provided, you get the output below:
string | CleanedString
-------------------------------------------|---------------------------------
(SCARF.) / (WRAPS) | SCARF-WRAPS
KRA!NTHI##KUMAR, KU%^?MAR GO~()$U.BigGrin | KRA-NTHI-KUMAR-KU-MAR-GO-U-BigGrin

Replace Value in Custom format for MS SQL

I have a set of data for example:
Part no Custom Format
1128005 \Machines\3D\PartNo(2)\PartNo(4)xx\PartNo(7)
11.88.006 \Machines\3D\PartNo(2)\PartNo+3(2)xx\PartNo+6(3)
I want to replace the variable set in the custom format define in it. The result i am looking for is
For Part no
1128005
the result is
\Machines\3D\11\1128xx\1128005
11.88.006
\Machines\3D\11\88xx\006
Any ideas?
Thanks
Regards
If my understanding is correct, below script should be what you want? But because it processes row by row, it can be very slow when dealing with millions of rows.
--declare #input varchar(50) = '11.88.006', #pattern varchar(255) = '\Machines\3D\PartNo(2)\PartNo+3(2)xx\PartNo+6(3)'
declare #input varchar(50) = '1128005', #pattern varchar(255) = '\Machines\3D\PartNo(2)\PartNo(4)xx\PartNo(7)'
declare #tblPattern table (tmpKey int identity(1,1), result varchar(50), Position varchar(50), SkipCnt int, CharLength int, Sufix varchar(50))
declare #i int = 1, #output varchar(max) = '\Machines\3D\'
Declare #PatternXml XML
Set #PatternXml = N'<root><r>' + REPLACE(replace(#pattern, '\Machines\3D\', ''), '\', '</r><r>') + '</r></root>'
insert into #tblPattern(result)
select r.value('.', 'VARCHAR(MAX)') as t
from #PatternXml.nodes('//root//r') as records(r)
update #tblPattern set Position = REPLACE(result, 'PartNo', '')
, SkipCnt = CASE WHEN CHARINDEX('+', result, 1) > 0 THEN SUBSTRING(result, CHARINDEX('+', result, 1) + 1, CHARINDEX('(', result, 1) - CHARINDEX('+', result, 1) - 1) ELSE 0 END
, CharLength = SUBSTRING(result, CHARINDEX('(', result, 1) + 1, CHARINDEX(')', result, 1) - CHARINDEX('(', result, 1) - 1 )
, Sufix = SUBSTRING(result, CHARINDEX(')', result, 1) + 1, LEN(result))
while #i <= 3
begin
select #output += SUBSTRING(#input, 1 + SkipCnt, CharLength) + Sufix + '\'
from #tblPattern
where tmpKey = #i
set #i += 1
end
select #output = STUFF(#output, len(#output), 1, '')
select #output

Change a string = '1 1/4' to '1.2500'

declare #Dimension = '1 1/4' varchar(20)
I want to change Dimension = '1 1/4' to Dimension = '1.2500'. I do not know how to split
a varchar into 2 varchar and change one part and then recombine then into a single varchar
UPDATE VF_CasINV_Cost
SET #Dimension = CASE
when (#Dimension like '%1/4') then
(left(#Dimension, charindex(' ', #Dimension, 1) - 1) *
(substring(#Dimension, 1 + charindex(' ', #Dimension, 1), len(#Dimension)))
end
where #Dimension like '%1/4'
what would be great to know how to parse the fraction and recal it into decimal on the fly
declare #x varchar(100)
select #x = '15 3/165'
select
convert(int, substring(#x, 1, charindex(' ', #x))) + (
convert(decimal(12,4), substring(#x, charindex(' ', #x) + 1, charindex('/', #x) - charindex(' ', #x) - 1)) /
convert(decimal(12,4), substring(#x, charindex('/', #x) + 1, len(#x) - charindex('/', #x)))
)
Payload beat me to it but one way is to;
declare #Dimension varchar(20) = '1 1/8'
declare #sql nvarchar(512) = 'set #out=' + replace(#Dimension, ' ',' + ') + '.00'
declare #result decimal(9,4)
execute sp_executesql #sql, N'#value varchar(30), #out decimal(9,4) output', #value=#Dimension, #out=#result output
select #result
isolate the fraction with substring and charindexing, then execute a select.
set #stringquery = SELECT "SELECT "+substring(#Dimension,1+charindex(' ',#Dimension,1),len(#Dimension);
execute sp_executesql #stringquery
This should handle and fraction after a space.
actually, thinking about it - to do the whole equation, just replace the space with a + sign and run it through sp_executesql, this should (I havnt tested this right at this point) convert 1 1/4 to 1+1/4 and the standard math engine will do the division before the addition so it will end up as 1.25.
This script can handle more variations in dimension (x in the table)
declare #t table(x varchar(20))
insert #t values('1 1/2')
insert #t values('2')
insert #t values('2/3')
insert #t values('22 1/3')
select coalesce(cast(case when isnumeric(n1)=1 then n1 else 0 end + n2 / n3 as real), n1)
from
(
select case when isnumeric(x) = 1 then x else
left(x, patindex('%_ %', x)) end n1,
cast(stuff(stuff(x, patindex('%/%', x), charindex('/',reverse(x)), ''), 1,charindex(' ',x),'') as real) n2,
case when patindex('%_/%', reverse(x)) = 0 then null else
cast(right(x, patindex('%_/%', reverse(x))) as real) end n3
from #t
) a

Resources