October 18, 2010 at 1:37 pm
Hello Everyone
I am working on using part of a string to name the related graphic file.
This is an example of what I have:
1001W-Large.jpg
or
1778SMB-Small.jpg
There are no set number of characters before the hyphen, but all names have a hyphen.
What can I use to select only all characters to the left side of the hyphen? So that the value is:
1001W
or
1778SMB
I have tried SubString and CharIndex, but cannot seem to get it exact.
Thanks in advance
Andrew SQLDBA
October 18, 2010 at 1:50 pm
Is this what you asked for?
SELECT SUBSTRING(@name, 1, CHARINDEX('-', @name) -1)
OR
SELECT LEFT(@name, CHARINDEX('-', @name) -1)
October 18, 2010 at 1:56 pm
this works, andrew, but i've got an extra +1 and -1 in the mis that can be cleaned up for the "Descript" column:
/*
BaseFileName Descriptor Extension
1001W Large jpg
1778SMB Small jpg
ADifferentFilename Small jpeg
NoDashes NoDashes jpeg
*/
with myCTE as (SELECT '1001W-Large.jpg' As TheFilename UNION ALL
SELECT '1778SMB-Small.jpg' UNION ALL
SELECT 'ADifferentFilename-Small.jpeg' UNION ALL
SELECT 'NoDashes.jpeg')
SELECT
CASE
WHEN CHARINDEX('-',TheFileName) > 0
THEN LEFT(TheFilename,CHARINDEX('-',TheFileName) - 1) --minus one to REMOVE the dash
ELSE LEFT(TheFilename,CHARINDEX('.',TheFileName) - 1)
END AS BaseFileName,
CASE
WHEN CHARINDEX('-',TheFileName) > 0
THEN SUBSTRING(TheFilename,CHARINDEX('-',TheFileName) + 1,CHARINDEX('.',TheFileName) + 1 - (CHARINDEX('-',TheFileName) + 1) -1 )
ELSE SUBSTRING(TheFilename,1,CHARINDEX('.',TheFileName) + 1 - (CHARINDEX('-',TheFileName) + 1) -1)
END AS Descriptor,
REVERSE(LEFT(REVERSE(TheFilename),CHARINDEX('.',REVERSE(TheFilename)) - 1)) AS Extension
FROM myCTE
Lowell
October 18, 2010 at 1:57 pm
Thanks WildCat
I figured it out right after another coffee.
I will keep your sample code for future queries.
Thanks again
Andrew SQLDBA
October 24, 2010 at 12:32 pm
AndrewSQLDBA (10/18/2010)
Thanks WildCatI figured it out right after another coffee.
I will keep your sample code for future queries.
Thanks again
Andrew SQLDBA
Two way street here, Andrew... can you please post what it is that you figure out? Thanks.
--Jeff Moden
Change is inevitable... Change for the better is not.
October 24, 2010 at 1:20 pm
This is what I used to get the value that I needed
DECLARE @ProductName varchar(50)
SET @ProductName = '10494B-XL-Large.jpg'
SELECT SUBSTRING(@ProductName, 1, CHARINDEX('-', @ProductName) -1)
And the result is
10494B
Andrew SQLDBA
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply