I am querying a table that contains a comments section. The comments section can contain part numbers of variable lengths. If, within the comments section I ensure that the part numbers are wrapped in quotes ("partnumberA"), is it possible query that field to pull everything in between the quotes (even if the part numbers could vary in length)?
Production notes are stored in an NVARCHAR field. Here is some sample data:
3/6/2015 (blujo) - "3490-0001023-02" PO46709 Due 3/10 (RW24718)
You can use a combination of substring and charindex functions.
declare #Comments varchar(50)
set #Comments = '3/6/2015 (blujo) - "3490-0001023-02" PO46709 Due 3/10 (RW24718)'
select substring(#Comments,
charindex('"',#Comments)+1,
charindex('"',#Comments,
charindex('"',#Comments)+1)-charindex('"',#Comments)-1)
The first charindex finds the first quote and starts on the following character. The second and third charindex finds the next quote after the first.
If the length of the part number is standard (say 6 characters), you could always try a SUBSTRING, CHARINDEX mix:
SELECT SUBSTRING(Comments, CHARINDEX('"', Comments) - 1, CHARINDEX('"', Comments) + 6)
FROM Table
This would start your substring just before the first double quote, and go until it finds the last double quote.
You can use CROSS APPLY to select the indices of successive occurences of the " character in your NVARCHAR field. Having these indices at hand, you can use SUBSTRING to extract the required part of the field:
SELECT SUBSTRING(ProductionNotes, First.x + 1, Second.x - First.x - 1)
FROM MyTable
CROSS APPLY (SELECT CHARINDEX('"', ProductionNotes)) AS First(x)
CROSS APPLY (SELECT CHARINDEX('"', ProductionNotes, First.x + 1)) AS Second(x)
First.x is the index of the 1st occurence of " in ProductionNotes field. The second occurence is located by feeding the previous index + 1, i.e. First.x + 1, as the start_location of CHARINDEX.
Here's a sample using a variable. Of course your query would reference a table column instead:
declare #x varchar(256) = '3/6/2015 (blujo) - "3490-0001023-02" PO46709 Due 3/10 (RW24718)';
select
substring(
#x,
charindex('"', #x) + 1,
charindex('"', #x, charindex('"', #x) + 1) - charindex('"', #x) - 1
)
Related
newbie here.
Want to know is there any chance to changes the words on sql server to * but only 50% of the datas?
Example :
select name from biodata
Result :
1. Mountain
2. Grace
3. Yellow
Expected result is
1. Moun****
2. Gr***
3. Yel***
Thabk you in advance
I think this does what you want, preserving the length of the word as well:
select word,
left(left(word, len(word) / 2.0) + replicate('*', len(word)), len(word))
from (values ('Mountain'), ('Grace'), ('Yellow')) v(word);
Try following:
select concat (
substring(Name, 1, LEN(Name)/2),
replicate('*', LEN(Name)/2)
)
from biodata
--> substring(Name, 1, LEN(Name)/2) will get first half of the name
--> replicate('*', LEN(Name)/2) will repeat * for the remaining half of the name
--> And finally, Concat() will join both the strings.
A combination of len(), stuff() and replicate() can get you there.
Use len() to get the length of the word. Use replicate() to create a string of asterisks of the needed length, and use stuff() to overwrite the end of the word with asterisks. You could also use left() and concatenation instead of stuff().
For example:
declare #string varchar(10) = 'abcdefghij'
select len(#string) -- returns 10
select left(#string, len(#string) / 2) -- returns 'abcde'
select replicate('*', len(#string) / 2) -- returns '*****'
select left(#string, len(#string) / 2) + replicate('*', len(#string) / 2) -- returns 'abcde*****'
I will leave it to you to decide how you want to handle strings with an odd number of characters, and how to organise the code neatly to work with a whole column rather than a single varaible. Note that the len() function is used repeatedly, so you can factor this out, for example, using cross apply.
My string looks something like this:
\\\abcde\fghijl\akjfljadf\\
\\xyz\123
I want to select everything between the 1st set and next set of slashes
Desired result:
abcde
xyz
EDITED: To clarify, the special character is always slashes - but the leading characters are not constant, sometimes there are 3 slashes and other times there are only 2 slashes, followed by texts, and then followed by 1 or more slashes, some more texts, 1 or more slash, so on and so forth. I'm not using any adapter at all, just looking for a way to select this substring in my SQL query
Please advise.
Thanks in advance.
You could do a cross join to find the second position of the backslash. And then, use substring function to get the string between 2nd and 3rd backslash of the text like this:
SELECT substring(string, 3, (P2.Pos - 2)) AS new_string
FROM strings
CROSS APPLY (
SELECT (charindex('\', replace(string, '\\', '\')))
) AS P1(Pos)
CROSS APPLY (
SELECT (charindex('\', replace(string, '\\', '\'), P1.Pos + 1))
) AS P2(Pos)
SQL Fiddle Demo
UPDATE
In case, when you have unknown number of backslashes in your string, you could just do something like this:
DECLARE #string VARCHAR(255) = '\\\abcde\fghijl\akjfljadf\\'
SELECT left(ltrim(replace(#string, '\', ' ')),
charindex(' ',ltrim(replace(#string, '\', ' ')))-1) AS new_string
SQL Fiddle Demo2
Use substring, like this (only works for the specified pattern of two slashes, characters, then another slash):
declare #str varchar(100) = '\\abcde\cc\xxx'
select substring(#str, 3, charindex('\', #str, 3) - 3)
Replace #str with the column you actually want to search, of course.
The charindex returns the location of the first slash, starting from the 3rd character (i.e. skipping the first two slashes). Then the substring returns the part of your string starting from the 3rd character (again, skipping the first two slashes), and continuing until just before the next slash, as determined by charindex.
Edit: To make this work with different numbers of slashes at the beginning, use patindex with regex to find the first alphanumeric character, instead of hardcoding that it should be the third character. Example:
declare #str varchar(100) = '\\\1Abcde\cc\xxx'
select substring(#str, patindex('%[a-zA-Z0-9]%', #str), charindex('\', #str, patindex('%[a-zA-Z0-9]%', #str)) - patindex('%[a-zA-Z0-9]%', #str))
APH's solution works better if your string always follows the pattern as described. However this will get the text despite the pattern.
declare #str varchar(100) = '\\abcde\fghijl\akjfljadf\\'
declare #srch char(1) = '\'
select
SUBSTRING(#str,
(CHARINDEX(#srch,#str,(CHARINDEX(#srch,#str,1)+1))+1),
CHARINDEX(#srch,#str,(CHARINDEX(#srch,#str,(CHARINDEX(#srch,#str,1)+1))+1))
- (CHARINDEX(#srch,#str,(CHARINDEX(#srch,#str,1)+1))+1)
)
Sorry for the formatting.
Edited to correct user paste error. :)
In SQL Server 2014, how can I extract all characters to the right of the first hyphen in a field where the first hyphen will have many combinations following it.
example 1:
Aegean-1GB-7days-COMP
desired result:
1GB-7days-COMP
example 2:
Aegean-SchooliesSpecial-7GB
desired result:
SchooliesSpecial-7GB
example 3:
AkCityOaks-1Day-3GB
desired result:
1Day-3GB
Using CHARINDEX AND SUBSTRING would work:
DECLARE #HTXT as nvarchar(max)
SET #HTXT='lkjhgf-wtrfghvbn-jk87fry--jk'
SELECT SUBSTRING(#HTXT, CHARINDEX('-', #HTXT) + 1, LEN(#HTXT))
Result:
wtrfghvbn-jk87fry--jk
You can use a combination of CharIndex and 'SubString' to get the desired result.
When you do this, you will get the location of the first hyphen starting from the first character.
CharIndex ('Aegean-1GB-7days-COMP', '-', 1)
Then cutting the string is easy
Select
SubString (
'Aegean-1GB-7days-COMP',
CharIndex ('-', 'Aegean-1GB-7days-COMP', 1) + 1,
Len('Aegean-1GB-7days-COMP') - CharIndex ('-', 'Aegean-1GB-7days-COMP', 1)
)
Since your data is most likely in a column, I would change this to
Select
SubString (
YourColumnName,
CharIndex ('-', YourColumnName, 1) + 1,
Len(YourColumnName) - CharIndex ('-', YourColumnName, 1)
)
From YourTableName
If you want to match -- instead of -, then look at PatIndex`
Read Here about CharIndex
Read Here about PatIndex
Read Here about SubString
Hi you can use PATINDEX and SUBSTRING like this:
DECLARE #Text NVARCHAR(4000)
DECLARE #StartPos int
SET #StartPos = PATINDEX('%-%',#Text) + 1
RETURN SUBSTRING(#Text,#StartPos,LEN(#Text)-#StartPos)
Or in one:
SUBSTRING([Text],PATINDEX('%A%',[Text]) + 1, LEN([Text]) - PATINDEX('%A%',[Text]) + 1)
I have a column with value
AAA_ZZZZ_7890_10_28_2014_123456.jpg
I need to replace the middle underscores so that it displays it as date i.e.
AAA_ZZZZ_7890_10-28-2014_123456.jpg
Can some one please suggest a simple update query for this.
The Number of Underscores would be same for all the values in the column but the length will vary for example some can have
AAA_q10WRQ_001_10_28_2014_12.jpg
The following should do it:
http://sqlfiddle.com/#!3/d41d8/30384/0
declare #filename varchar(64) = 'AAA_ZZZZ_7890_10_28_2014_123456.jpg'
declare #datepattern varchar(64) = '%[_][0-1][0-9][_][0-3][0-9][_][1-2][0-9][0-9][0-9][_]%'
select
filename,
substring(filename,1,datepos+2)+'-'+
substring(filename,datepos+4,2)+'-'+
substring(filename,datepos+7,1000)
from
(
select
#filename filename,
patindex(#datepattern,#filename)
as datepos
) t
;
Resulting in
AAA_ZZZZ_7890_10-28-2014_123456.jpg
Caveats to watch out for:
It is important to exactly define how you find the date. In my definition it is MM_DD_YYYY surrounded by further two underscores, and I check that the first digits of M,D,Y are 0-1,0-3,1-2 respectively (i.e. I do NOT check if month is e.g. 13.) -- of course we assume that there is only one such string in any file name.
datepos actually finds the position of the underscore before the date -- this is not an issue if taken into account in the indexing of substring.
in the 3rd substring the length cannot be NULL or infinity and I couldn't get LEN() to work in SQL Fiddle so I dirty hardcoded a large enough number (1000). Corrections to this are welcome.
Try this (assuming that the DATE portion always starts at the same character index)
declare #string varchar(64) = 'AAA_ZZZZ_7890_10_28_2014_123456.jpg'
select replace(#string, reverse(substring(reverse(#string), charindex('_', reverse(#string), 0) + 1, 10)), replace(reverse(substring(reverse(#string), charindex('_', reverse(#string), 0) + 1, 10)), '_', '-'))
If there are exactly 6 _ then for the first
select STUFF ( 'AAA_ZZZZ_7890_10_28_2014_123456.jpg' , CHARINDEX ( '_' ,'AAA_ZZZZ_7890_10_28_2014_123456.jpg', CHARINDEX ( '_' ,'AAA_ZZZZ_7890_10_28_2014_123456.jpg', CHARINDEX ( '_' ,'AAA_ZZZZ_7890_10_28_2014_123456.jpg', CHARINDEX ( '_' ,'AAA_ZZZZ_7890_10_28_2014_123456.jpg', 0 ) + 1 ) + 1 ) + 1 ) , 1 , '-' )
We have the below in row in MS SQL:
Got event with: 123.123.123.123, event 34, brown fox
How can we extract the 2nd number ie the 34 reliable in one line of SQL?
Here's one way to do it using SUBSTRING and PATINDEX -- I used a CTE just so it wouldn't look so awful :)
WITH CTE AS (
SELECT
SUBSTRING(Data,CHARINDEX(',',Data)+1,LEN(Data)) data
FROM Test
)
SELECT LEFT(SUBSTRING(Data, PATINDEX('%[0-9]%', Data), 8000),
PATINDEX('%[^0-9]%',
SUBSTRING(Data, PATINDEX('%[0-9]%', Data), 8000) + 'X')-1)
FROM CTE
And here is some sample Fiddle.
As commented, CTEs will only work with 2005 and higher. If by chance you're using 2000, then this will work without the CTE:
SELECT LEFT(SUBSTRING(SUBSTRING(Data,CHARINDEX(',',Data)+1,LEN(Data)),
PATINDEX('%[0-9]%', SUBSTRING(Data,CHARINDEX(',',Data)+1,LEN(Data))), 8000),
PATINDEX('%[^0-9]%',
SUBSTRING(SUBSTRING(Data,CHARINDEX(',',Data)+1,LEN(Data)),
PATINDEX('%[0-9]%', SUBSTRING(Data,CHARINDEX(',',Data)+1,LEN(Data))), 8000) + 'X')-1)
FROM Test
Simply replace #s with your column name to apply this to a table. Assuming that number is between last comma and space before the last comma. Sql-Fiddle-Demo
declare #s varchar(100) = '123.123.123.123, event 34, brown fox'
select right(first, charindex(' ', reverse(first),1) ) final
from (
select left(#s,len(#s) - charindex(',',reverse(#s),1)) first
--from tableName
) X
OR if it is between first and second commas then try, DEMO
select substring(first, charindex(' ',first,1),
charindex(',', first,1)-charindex(' ',first,1)) final
from (
select right(#s,len(#s) - charindex(',',#s,1)-1) first
) X
I've thought of another way that's not been mentioned yet. Presuming the following are true:
Always one comma before the second "part"
It's always the word "event" with the number in the second part
You are using SQL Server 2005+
Then you could use the built in ParseName function meant for parsing the SysName datatype.
--Variable to hold your example
DECLARE #test NVARCHAR(50)
SET #test = 'Got event with: 123.123.123.123, event 34, brown fox'
SELECT Ltrim(Rtrim(Replace(Parsename(Replace(Replace(#test, '.', ''), ',', '.'), 2), 'event', '')))
Results:
34
ParseName parses around dots, but we want it to parse around commas. Here's the logic of what I've done:
Remove all existing dots in the string, in this case swap them with empty string.
Swap all commas for dots for ParseName to use
Use ParseName and ask for the second "piece". In your example this gives us the value
" event 34".
Remove the word "event" from the string.
Trim both ends and return the value.
I've no comments on performance vs. the other solutions, and it looks just as messy. Thought I'd throw the idea out there anyway!