SQL - SELECT all the records limiited to certain characters - sql

I am pretty new to SQL so I desperately need support with the following matter:
one of the columns of the table I am querying contains very long and various text values: so, I would like to limit the output to some kinds only.
I would like to get as output of the query the same content, limited to [a-z][A-Z][0-9], so for example:
Original table: Hello /% World, 2019
Result query: Hello World 2019
Does anybody have any idea?
Thank you very much

Assuming regexp_replace is supported,
regexp_replace(column, '[^a-zA-Z0-9]', '')

You didn't mention which SQL engine you are using, but most engines support the string function REPLACE which can use to substitute any character you want with an empty string to remove it. You will have to nest several of these to get rid of the different characters. Check the documentation of your database engine for the syntax.
For example:
SELECT REPLACE(REPLACE('Hello /% World, 2019, '/', ''), '%','')
In general, I would argue that this is not the job of the database engine, and you can do it in your presentation layer.
HTH

$string = 'Hello /% World, 2019';
Strip all characters but letters and numbers from a PHP string:
$res = preg_replace("/[^a-zA-Z0-9]/", "", $string);
Strip all characters but letters, numbers, and whitespace:
$res = preg_replace("/[^a-zA-Z0-9\s]/", "", $string);

BEST OPTION: Remove all special characters leaving no spaces
SELECT REGEXP_REPLACE(your_column, '[^0-9A-Za-z]', '') AS newfield
FROM tablename;
Remove many characters, leaving spaces for the same number of characters removed
SELECT TRANSLATE(columnname,'!##$%^&*()',
' ' ) AS newfield
FROM tablename;
If you just want to replace one character
SELECT REPLACE('columnname', '%', '') AS newfield
From tablename;
If you are looking for something in particular (You want to find the words "Hello World 2019")
Select ‘Hello World 2019' AS newfield
From tablename
WHERE columnname like ‘Hello%’ AND columnname like ‘%World%’ AND columnname like ‘%2019’;
Assuming Hello is always the beginning and 2019 is always at the end and you want all the fields. If you want other fields, you might want those as well; like,
Select TableID, columnname, ‘Hello World 2019' AS newfield
From tablename
WHERE columnname like ‘Hello%’ AND columnname like ‘%World%’ AND columnname like ‘%2019’;

Related

Getting unwanted data in select statement of NChar column

On running the below query:
SELECT DISTINCT [RULE], LEN([RULE]) FROM MYTBL WHERE [RULE]
LIKE 'Trademarks, logos, slogans, company names, copyrighted material or brands of any third party%'
I am getting the output as:
The column datatype is NCHAR(120) and the collation used is SQL_Latin1_General_CP1_CI_AS
The data is inserted with an extra leading space in the end. But using RTRIM function also I am not able to trim the extra space. I am not sure which type of leading space(encoded) is inserted here.
Can you please suggest some other alternative except RTRIM to get rid of extra white space at the end as the Column is NCHAR.
Below are the things which I have already tried:
RTRIM(LTRIM(CAST([RULE] as VARCHAR(200))))
RTRIM([RULE])
Update to Question
Please download the Database from here TestDB
Please use below query for your reference:
SELECT DISTINCT [RULE], LEN([RULE]) FROM [TestDB].[BI].[DimRejectionReasonData]
WHERE [RULE]
LIKE 'Trademarks, logos, slogans, company names, copyrighted material or brands of any third party%'
You may have a non-breaking space nchar(160) inside the string.
You can convert it to a simple space and then use the usual trim function
LTRIM(RTRIM(REPLACE([RULE], NCHAR(160), ' ')))
In case of unicode space
LTRIM(RTRIM(REPLACE(RULE, NCHAR(0x00A0), ' ')))
I guess this is what you are looking for ( Not sure ) . Make a try with this approach
SELECT REPLACE(REPLACE([RULE], CHAR(13), ''), CHAR(10), '')
Reference links : Link 1 & Link 2
Note: FYI refer those links for better understanding .
change the type nchar into varchar it will return the result without extra space

Oracle db query - data format issue

I'm wondering if there is a way to query the oracle db against formatted field value.
Example:
I have a table of postcodes stored in the format of "part1 part2". I want to be able to find a postcode either by searching it using the above format or "part1part2" format.
What I was thinking is to format the entered postcode by removing the spaces and then query the database like:
SELECT *
FROM POSTCODES_TBL t
WHERE t.postcode.**Format(remove spaces)** = 'part1part2'
The Format(remove spaces would convert the postcode from "part1 part2" to "part1part".
My question is, is it possible?
You can use regexp_replace
SELECT *
FROM POSTCODES_TBL t
WHERE regexp_replace(t.postcode,'\s', '') = 'part1part2'
This will remove any whitespace (space, tab, newlines etc)
or if you only want to get rid of spaces, replace will work just as well:
SELECT *
FROM POSTCODES_TBL t
WHERE replace(t.postcode,' ', '') = 'part1part2'
More details in the manual:
replace
regexp_replace
You could use like
SELECT *
FROM POSTCODES_TBL t
WHERE t.postcode like 'part1%part2'

Search special characters from SQL table

Text = “World“ world ” <world <Word> ‘ word’ ‘ word“ word’ =1254.25 = 2545.58. 20%
Hey guys,
I need to search a word from a string which was saved in my db. The searching word contains special characters such as ""'!##$%^<>. Below is the sql select query used for the search.
select * from TABLE where TABLE.text like ('%'+ '“ World' +'%')
as a result some of the special character are not searched. Characters such as double quotation, single quotation are not searched from this. need assistance with solving this problem asap. thank you :)
These Special characters are Unicode characters, When ever dealing with these characters in sql server you have to tell sql server explicitly that there can be some unicode characters in the strings you are about to manipulate by prefixing your strings with N'String'
In your case you would write a query something like ....
select * from TABLE
where TABLE.text like N'%'+ N'“ World' + N'%'
you can use the ESCAPE clause and escape your parameter value. http://technet.microsoft.com/en-us/library/ms179859.aspx
so for example to search for a string containing the character %
select * from TABLE where TABLE.text like ('%'+ N'\%' +'%') ESCAPE '\'

Search for “whole word match” with SQL Server LIKE pattern

Does anyone have a LIKE pattern that matches whole words only?
It needs to account for spaces, punctuation, and start/end of string as word boundaries.
I am not using SQL Full Text Search as that is not available. I don't think it would be necessary for a simple keyword search when LIKE should be able to do the trick. However if anyone has tested performance of Full Text Search against LIKE patterns, I would be interested to hear.
Edit:
I got it to this stage, but it does not match start/end of string as a word boundary.
where DealTitle like '%[^a-zA-Z]pit[^a-zA-Z]%'
I want this to match "pit" but not "spit" in a sentence or as a single word.
E.g. DealTitle might contain "a pit of despair" or "pit your wits" or "a pit" or "a pit." or "pit!" or just "pit".
Full text indexes is the answer.
The poor cousin alternative is
'.' + column + '.' LIKE '%[^a-z]pit[^a-z]%'
FYI unless you are using _CS collation, there is no need for a-zA-Z
you can just use below condition for whitespace delimiters:
(' '+YOUR_FIELD_NAME+' ') like '% doc %'
it works faster and better than other solutions. so in your case it works fine with "a pit of despair" or "pit your wits" or "a pit" or "a pit." or just "pit", but not works for "pit!".
I think the recommended patterns exclude words with do not have any character at the beginning or at the end. I would use the following additional criteria.
where DealTitle like '%[^a-z]pit[^a-z]%' OR
DealTitle like 'pit[^a-z]%' OR
DealTitle like '%[^a-z]pit'
I hope it helps you guys!
Surround your string with spaces and create a test column like this:
SELECT t.DealTitle
FROM yourtable t
CROSS APPLY (SELECT testDeal = ' ' + ISNULL(t.DealTitle,'') + ' ') fx1
WHERE fx1.testDeal LIKE '%[^a-z]pit[^a-z]%'
If you can use regexp operator in your SQL query..
For finding any combination of spaces, punctuation and start/end of string as word boundaries:
where DealTitle regexp '(^|[[:punct:]]|[[:space:]])pit([[:space:]]|[[:punct:]]|$)'
Another simple alternative:
WHERE DealTitle like '%[^a-z]pit[^a-z]%' OR
DealTitle like '[^a-z]pit[^a-z]%' OR
DealTitle like '%[^a-z]pit[^a-z]'
This is a good topic and I want to complement this to someone how needs to find some word in some string passing this as element of a query.
SELECT
ST.WORD, ND.TEXT_STRING
FROM
[ST_TABLE] ST
LEFT JOIN
[ND_TABLE] ND ON ND.TEXT_STRING LIKE '%[^a-z]' + ST.WORD + '[^a-z]%'
WHERE
ST.WORD = 'STACK_OVERFLOW' -- OPTIONAL
With this you can list all the incidences of the ST.WORD in the ND.TEXT_STRING and you can use the WHERE clausule to filter this using some word.
You could search for the entire string in SQL:
select * from YourTable where col1 like '%TheWord%'
Then you could filter the returned rows client site, adding the extra condition that it must be a whole word. For example, if it matches the regex:
\bTheWord\b
Another option is to use a CLR function, available in SQL Server 2005 and higher. That would allow you to search for the regex server-side. This MSDN artcile has the details of how to set up a dbo.RegexMatch function.
Try using charindex to find the match:
Select *
from table
where charindex( 'Whole word to be searched', columnname) > 0

SQL (MySQL): Match first letter of any word in a string?

(Note: This is for MySQL's SQL, not SQL Server.)
I have a database column with values like "abc def GHI JKL". I want to write a WHERE clause that includes a case-insensitive test for any word that begins with a specific letter. For example, that example would test true for the letters a,c,g,j because there's a 'word' beginning with each of those letters. The application is for a search that offers to find records that have only words beginning with the specified letter. Also note that there is not a fulltext index for this table.
You can use a LIKE operation. If your words are space-separated, append a space to the start of the string to give the first word a chance to match:
SELECT
StringCol
FROM
MyTable
WHERE
' ' + StringCol LIKE '% ' + MyLetterParam + '%'
Where MyLetterParam could be something like this:
'[acgj]'
To look for more than a space as a word separator, you can expand that technique. The following would treat TAB, CR, LF, space and NBSP as word separators.
WHERE
' ' + StringCol LIKE '%['+' '+CHAR(9)+CHAR(10)+CHAR(13)+CHAR(160)+'][acgj]%'
This approach has the nice touch of being standard SQL. It would work unchanged across the major SQL dialects.
Using REGEXP opearator:
SELECT * FROM `articles` WHERE `body` REGEXP '[[:<:]][acgj]'
It returns records where column body contains words starting with a,c,g or i (case insensitive)
Be aware though: this is not a very good idea if you expect any heavy load (not using index - it scans every row!)
Check the Pattern Matching and Regular Expressions sections of the MySQL Reference Manual.