Is it possible to use stuff function with a condition.
I'm trying to create a regex pattern from the values in SQL table.
My stuff function looks like this:
stuff(name,patindex('%Apple%',name),len(name),'%')
But I also need to run
stuff(name,patindex('%Mango%',name),len(name),'%')
Can I do both in the same stuff function with a OR condition?
Your exact logic or expected result is not entirely clear, but you could try writing the above using a CASE expression:
STUFF(name,
CASE WHEN PATINDEX('%Apple%', name) < PATINDEX('%Mango%', name)
THEN PATINDEX('%Apple%', name)
ELSE PATINDEX('%Mango%', name) END,
LEN(name), '%')
The logic here is to choose the starting point for the STUFF operation based on which fruit substring appears first in the name.
Related
...Hi, a database ingenue here. I'm trying to figure out how to use LIKE with CASE in SQLite, or some equivalent approach. I've got a prod_names table that contains concatenated data--occasionally just 1 item, but usually containing several comma-separated items. For my new 'Toy' column, I need to find every record that contains 'CapGun'. The code below works only when 'CapGun' is the only item, and not when there are multiple items (eg, 'BarbieDoll, CapGun, EasyBakeOven').
SELECT
customer_id,
prod_names,
CASE prod_names WHEN 'CapGun' THEN 'CG' ELSE 'not_CG' END Toy
FROM
Toys_table
ORDER BY
Toy
I've tried various approaches like WHEN LIKE '%CapGun%', WHEN INSTR(prod_names,'CapGun') > 0, and WHEN GLOB '*CapGun*' but they all return no results or throw a syntax error.
Any suggestions? I'm sure there must be a simple solution.
Use the expanded case syntax:
CASE
WHEN prod_names LIKE '%CapGun%' THEN ...
ELSE ...
END
This lets use any expression as the condition in your CASE, including other columns.
I’m working on this dataset to cleaning it
https://www.kaggle.com/heesoo37/120-years-of-olympic-history-athletes-and-results, using Dremio (an online tool) so I can use an SQL editor (but i don't know what DBMS it use).
Now I’m trying to delete from the column Event the words that are contained in the column Sport. (I’ve already done some modification indeed in the column Event I’ve deleted the occurance of the words “man’s” and “women’s”).
Attached you’ll find
The current situtation and the desired result
How can I solve the problem?
I hope I have been clear, Thank you in advance for help. :)
Edit: I've found the original query made by Dremio
SELECT ID, Name, Gender, Age, Height, Weight, Team, "Olympic Games"."Year" AS "Year", Season, City, Sport, CASE WHEN regexp_like(CASE WHEN regexp_like(Event, '.*?\QMen''s\E.*?') THEN regexp_replace(Event, '\QMen''s\E', '') ELSE Event END, '.*?\QWomen''s\E.*?') THEN regexp_replace(CASE WHEN regexp_like(Event, '.*?\QMen''s\E.*?') THEN regexp_replace(Event, '\QMen''s\E', '') ELSE Event END, '\QWomen''s\E', '') ELSE CASE WHEN regexp_like(Event, '.*?\QMen''s\E.*?') THEN regexp_replace(Event, '\QMen''s\E', '') ELSE Event END END AS Event, Medal
FROM "#Sboorn"."Olympic Games"
WHERE NOT regexp_like(ID, '.*?\QID\E.*?')
You can use a CASE to heck if event starts with the sport and a space. If so use substring() to omit the first n characters for n the length of sport and the space. Else return event unchanged.
SELECT sport,
CASE
WHEN event LIKE concatenate(sport, ' %') THEN
substring(event, length(sport) + 2, length(event) - length(sport) - 1)
ELSE
event
END event
FROM elbat;
As you didn't tag your actual DBMS, the names of the functions might differ (e.g. concat() instead of concatenate(), substr() instead of substring() or len() instead of length()). But some equivalent should be available in most DBMS.
Depending on the actual DBMS there also might be more elegant solutions, like regular expressions.
And next time please don't post images. Use CREATE TABLE and INSERT INTO statements to show how your tables look like and plain text to show the desired result.
I would like to build one sql query in that one of my filed of form should not contain common names (maintained list of words in separate table) and i am passing value of that filed as parameter and want to check that it shouldn't contain any common name from that table.
How can i achieve that using sql query?
Note : if common name is 'abc' and i am passing parameter as '!abc123' since it contains that word query should return false.
Thanks in advance.
Try something like (Untested Query):
SELECT CommonName
FROM CommonNamesTable
WHERE CommonName like '%NameToTest%'
OR CONTAINS(NameToTest, CommonName);
Basically you need the string match options:
Take a look at options of CONTAINS and read about Queries with full text search
Is this what you're looking for?
SELECT (COUNT(*) == 0) FROM tablewithcommonwords
WHERE wordfromform LIKE CONCAT('%', wordcolumnnfromcommonwordstable, '%');
Try this:
IF NOT EXISTS(SELECT word FROM CommonWord WHERE #yourparam
LIKE '%' + word + '%')
BEGIN
RETURN 1
END
ELSE
BEGIN
Return 0
END
This works if the #yourParam is contained in any word or name, what you do not want to use. It only returns 1 if it is not contained by any row in the table.
I worte this sentence only on this way (you can use a simple Exists instead of NOT Exists), because may you want to extend the functionality in the true part.
if exists (select * from reservedwords where #parameter like '%'+word + '%')
select 0
else
select 1
I would like to suggest that You have to use keypress Event in Your TextBox and then Handle your Code after Each character enter in your TextBox.
I'm writing some very simple search functionality for a list of FAQ's. I'm splitting the search string on a variety of characters, including spaces. Then performing a select along the lines of
SELECT *
FROM "faq"
WHERE
((LOWER("Question") LIKE '%what%'
OR LOWER("Question") LIKE '%is%'
OR LOWER("Question") LIKE '%a%'
OR LOWER("Question") LIKE '%duck%'))
I've had to edit this slightly as its generated by our data access layer but it should give you an idea of whats going on.
The problem is demonstrated well with the above query in that most questions are likely to have the words a or is in them, however I can not filter these out as acronyms may well be important for the searcher. What has been suggested is we order by the number of matching keywords. However I have been unable to find a way of doing this in SQL (we do not have time to create a simple search engine with an index of keywords etc). Does anyone know if there's a way of counting the number of LIKE matches in an SQL statement and ordering by that so that the questions with the most keywords appear at the top of the results?
I assume the list of matching keywords is being entered by the user and inserted into the query dynamically by the application, immediately prior to executing the query. If so, I suggest amending the query like so:
SELECT *
FROM "faq"
WHERE
((LOWER("Question") LIKE '%what%'
OR LOWER("Question") LIKE '%is%'
OR LOWER("Question") LIKE '%a%'
OR LOWER("Question") LIKE '%duck%'))
order by
case when LOWER("Question") LIKE '%what%' then 1 else 0 end +
case when LOWER("Question") LIKE '%is%' then 1 else 0 end +
case when LOWER("Question") LIKE '%a%' then 1 else 0 end +
case when LOWER("Question") LIKE '%duck%' then 1 else 0 end
descending;
This would even enable you to "weight" the importance of each selection term, assuming the user (or an algorithm) could assign a weighting to each term.
One caveat: if your query is being constructed dynamically, are you aware of the risk of SQL Insertion attacks?
You can write a function which counts the occurrences of one string in another like this:
CREATE OR REPLACE FUNCTION CountInString(text,text)
RETURNS integer AS $$
SELECT(Length($1) - Length(REPLACE($1, $2, ''))) / Length($2) ;
$$ LANGUAGE SQL IMMUTABLE;
And use it in the select: select CountInString("Question",' what ') from "faq".
Is there something I can put in my WHERE clause to only select fields from a column where that field does not contain a certain string. In this case, I am looking through to make sure the codes in this particular field do not have a "cs" in it. The code could be something like cs023 or bg425, just to give you a little bit more of an idea what I'm looking to do.
You can use
WHERE [column] NOT LIKE '%cs%'
Replace [column] with your column name.
Just a couple of alternatives (for folks who like VB's InStr() or JS' .indexOf() type syntax).
WHERE CHARINDEX('cs', [column]) = 0;
...or...
WHERE PATINDEX('%cs%', [column]) = 0;
You might also want to deal with NULL values:
WHERE COALESCE([column], '') NOT LIKE '%cs%';