In SQL Server 2012, I have a column which has long text data. Somewhere within the text, there is some text of the format
{epa_file_num} = {138410-81}
If it exists, I want to extract out 138410-81 as a column value. In regular JS regex, I would use something like this { *epa_file_num *} *= *{ *\d*-?\d* *} to match the column, and then maybe a capturing group to get the value.
But how can I get it in SQL Server 2012?
Thanks
Not a regex, but this might do what you want:
DECLARE #Input VARCHAR(MAX)='{some name} = {a value} some text {epa_file_num} = {138410-81} other text'
SET #Input=REPLACE(#Input,' ','')
SET #Input=SUBSTRING(#Input,NULLIF(PATINDEX('%{epa_file_num}={%',#Input),0)+LEN('{epa_file_num}={'),LEN(#Input))
SET #Input=SUBSTRING(#Input,1,NULLIF(CHARINDEX('}',#Input),0)-1)
SELECT #Input
First, I remove all the spaces, then I look for {epa_file_num}= and take everything after this string, until the next }.
Related
i have a table on sql like this:
CD_MATERIAL | CD_IDENTIFICACAO
1 | 002323
2 | 00322234
... | ...
AND SO ON (5000+ lines)
I need to use that info to search and replace multiple external xml files on a folder (all the tags on those XML had numbers like the CD_IDENTIFICACAO from sql query, i need to replace with corresponding cd_material from sql query "ex.: 002323 becomes 1)
I used this query to extract all the cd_identificacao to use on Notepad++:
declare #result varchar(max)
select #result = COALESCE(#result + '', '') + CONCAT('(',CD_IDENTIFICACAO,')|') from TBL_MATERIAIS WHERE CD_IDENTIFICACAO <> '' ORDER BY CD_MATERIAL
select #result
That would bring me ex.:
(1TEC45D025)|(1TEC800039)|(999999999)|(542251)|(2TEC58426)|(234852)
and changed the parameters to get the replace ex.:
(? 2000)|(? 2001)|(? 2002)|(? 2003)|(? 2004)|(? 2005)
but i don't know how to add a number (increment) on front of "?" so notepad++ would understand it (search and replace would have 5000+ results, so it's not pratical to manually add the increment).
I was able to get a workaround for this. I've used this query to get all the the terms for find and replace i needed (1 per line)
select concat('<cProd>',cd_identificacao,'</cProd>'), concat('<cProd>',cd_material,'</cProd>') from tbl_materiais where cd_identificacao <> '' order by cd_material
That would result in:
<cProd>1TEC460054</cProd> <cProd>1</cProd>
<cProd>1TEC240035</cProd> <cProd>2</cProd>
(i added the tag too to make sure no other information could be replaced as there were many number combinations that could lead to incorrect replacement)
then pasted it on a txt and i used the notepad++ to replace the space between column 1 and 2 for /r/n wich would result in:
<cProd>1TEC460054</cProd>
<cProd>1</cProd>
<cProd>1TEC240035</cProd>
<cProd>2</cProd>
then i used "Ecobyte Replace Text" Tool, pasted my result file as new selection in bottom frame, loaded all my files on a new replace group on top frame (on properties of the group, u can change directory and options), then executed the replacement, it worked perfectly.
Thx.
I have a table storing pathes to files on sql server. I need to replace the path before the last backslash:
C:\Users\APP\AppData\Local\Temp\test\abc deg.pdf
to for example:
\app\pp\abc deg.pdf
EDIT: The table containts many pathes - I need to run through the whole table and change all pathes.
You can use:
CHARINDEX('\', REVERSE(#str))
to get the index of the first backslash starting from the end.
Using RIGHT with this index you can extract the string after the last backslash and concatenate it to the new path:
DECLARE #str VARCHAR(50) = 'C:\Users\APP\AppData\Local\Temp\test\abc deg.pdf'
SELECT '\app\pp' + RIGHT(#str, CHARINDEX('\', REVERSE(#str)))
Reverse the input string (using REVERSE) and find the index of the first backslash (using CHARINDEX).
Take the left part up to that index (using LEFT) and concatenate with the reverse of your replacement string (using + operator).
Then reverse that to get your final result.
Try this:
declare #a varchar(max)='C:\Users\APP\AppData\Local\Temp\test\abc deg.pdf'
select REPLACE(#a,SUBSTRING(#a,1,(LEN(#a)-charindex('\',reverse(#a),1))),'\app\pp')
Update: For updatingall the table column values.
select REPLACE([column-name],SUBSTRING([column-name],1,(LEN([column-name])-charindex('\',reverse([column-name]),1))),'\app\pp')
FROM [Your-table]
This is how it can be done.
UPDATE TABLE
SET PATH = REPLACE(PATH, 'C:\Users\APP\AppData\Local\Temp\test', '\app\pp')
WHERE ...
This is going to replace 'C:\Users\APP\AppData\Local\Temp\test' with '\app\pp'. Or you can modify the path as required.
Please test before executing this UPDATE statement. I havent specified filters here
I know there are a few about similar topics on here but I can't find one related to my issue, this is it:
I have a table with an ID Column and a QRCode column. each time an item is added the primary key auto increments. The QRCode will scan in to be like the following:
"http://somewebsite.com/12345/987654321"
i want to be able to remove the "http://somewebsite.com/" from the string, I know how to do this in C# however I am unsure of how to do this in Sql Server. any guidance would be great, thanks
Regular formats are like the following, and used in the example below.
"http://somewebsite.com/12345/456564654"
"http://somewebsite.com/12345/989886765"
"http://somewebsite.com/12346/987654321"
the query returns the following results:
SELECT
REPLACE
(
REPLACE(QRCode, 'http://somewebsite.com/', '')
,'/', ' '
) AS QRCode
FROM
QRTable
WHERE
QRCode LIKE '%http://somewebsite.com/%'
"12345 456564654"
"12345 989886765"
"12346 987654321"
Now i need to update the table with those new results however as there's 3 results, i get the error message "Subquery returned more than 1 value". is there a way to replace the selected values in the table with the ones that exist based on the primary key field?
**Removed previous example
A more complete answer based on your updated question. This removes the first portion of the URL as well as the trailing / so that you get your desired output.
DECLARE #Variable VARCHAR(50)
SET #Variable = 'http://somewebsite.com/12345/456564654'
SET #Variable =
REPLACE
(
REPLACE(#Variable, 'http://somewebsite.com/', '')
,'/', ' '
)
PRINT #Variable
Output = 12345 456564654
Looking at your SQL statement you want this:
SELECT
REPLACE
(
REPLACE(QRCode, 'http://somewebsite.com/', '')
,'/', ' '
) AS QRCode
FROM
QRTable
WHERE
QRCode LIKE '%http://somewebsite.com/%'
I have a text file that contains Persian words and is saved using ANSI encoding. When I try to read the Persian words from the text file, I get some characters like '?'. To solve the problem, I changed the file encoding to UTF8 and re-wrote the text file. Here's the method for changing file encoding:
public void Convert2UTF8(string filePath)
{
//first, read the text file with "ANSI" endocing
StreamReader fileStream = new StreamReader(filePath, Encoding.Default);
string fileContent = fileStream.ReadToEnd();
fileStream.Close();
//Now change the file encoding and replace it with the UTF8
StreamWriter utf8Writer = new StreamWriter(filePath.Replace(".txt", ".txt"), false, Encoding.UTF8);
utf8Writer.Write(fileContent);
utf8Writer.Close();
}
Now the first problem is solved; However, there is another issue here: every time that I want to search a Persian word from the SQL server database table, the result is null while the record does exist in the database table.
What's the solution to find my Persian words that exist in the table? The code that I currently use is simply like the following:
SELECT * FROM [dbo].[WordDirectory]
WHERE Word = N'کلمه'
Word is the field that Persian words are saved in. The type of the field is NVARCHAR. My SQL server version is 2012.
Should I change the collation?
DECLARE #Table TABLE(Field NVARCHAR(4000) COLLATE Frisian_100_CI_AI)
INSERT INTO #Table (Field) VALUES
(N'همهٔ افراد بش'),
(N'میآیند و حیثیت '),
(N'ميشه آهسته تر صحبت کنيد؟'),
(N'روح'),
(N' رفتار')
SELECT * FROM #Table
WHERE Field LIKE N'%آهسته%'
The both Queries return the same result
RESULT Set: ميشه آهسته تر صحبت کنيد؟
You have to make sure that when you are inserting the values you prefix then witn N thats to tell sql server there can be unicode character in the passed string. Same is true when you are searching for them strings in Select statement.
Probably you have problem with Persian and Arabic versions of the 'ي' and 'ك' during search. These characters even look the same, have different Unicode numbers:
select NCHAR(1740), -- Persian ى
NCHAR(1610), -- Arabic ي
NCHAR(1705), -- Persian ك
NCHAR(1603) -- Arabic ك
more info: http://www.dotnettips.info/post/90
I have an interesting SQL Server search requirement.
Say I have a table with Part Numbers as follows:
PARTNO DESCRIPTION
------ -----------
ABC-123 First part
D/12a92 Second Part
How can I create a search that will return results if I search, say, for 'D12A'?
I currently have a full text search set up for the description column, but I am looking to find parts that match the part no even when users don't include the / or - etc.
I'd rather do this in a single SQL statement rather than creating functions if possible as we only have read access to the DB.
You could do something like:
SELECT * FROM PART_TABLE
WHERE REPLACE(REPLACE(PARTNO,'/', ''),'-','') LIKE '%D12A%'
This would work for the 2 characters you specified and could be extended for more character like so:
SELECT * FROM PART_TABLE
WHERE REPLACE(REPLACE(REPLACE(PARTNO,'/', ''),'-',''),*,'') LIKE '%D12A%'
Probably not the most elegant of solutions unless your special characters are limited. Otherwise I'd suggest writing a Function to strip out non-alphanumeric characters.
Here is an example of such a function:
CREATE FUNCTION dbo.udf_AlphaNumericChars
(
#String VARCHAR(MAX)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE #RemovingCharIndex INT
SET #RemovingCharIndex = PATINDEX('%[^0-9A-Za-z]%',#String)
WHILE #RemovingCharIndex > 0
BEGIN
SET #String = STUFF(#String,#RemovingCharIndex,1,'')
#RemovingCharIndex = PATINDEX('%[^0-9A-Za-z]%',#String)
END
RETURN #String
END
------- Query Sample (untested)---------
SELECT *
FROM PART_TABLE
WHERE DBO.udf_AlphaNumericChars(PARTNO) LIKE '%D12A%'
Taken From: http://sqlserver20.blogspot.co.uk/2012/06/find-alphanumeric-characters-only-from.html