I have an Access query. I need a mass 'like' criteria.
Normally it's "Like "Apple" or "Orange"". However, I have over 400 words.
How do make this happen without manually typing in a Like formula by hand with the 400 words?
Is there a way to do this by referencing a table or form?
As for "referencing a table", you can actually do a join using LIKE instead of =.
SELECT
t.*
FROM
target t
INNER JOIN
SearchList s
ON t.name LIKE '%' + s.term '%'
In this case, SearchList is a table you create just for this task with just 1 column containing the terms you want to search for.
You can use in clause , sub query to get result, the query in Access can have 64000 characters so your 400 words X 5 chars in each approximate , 2000 chars + 50 chars SQL statement, should be OK,
Select * from tblVitalInfo where ObjectName in ('Apple','Banana','Pitch')
But I will recommend following better way of doing same,
Assume the table tblVitalInfo(ID, ObjectName) , and searching ObjectName
I would create a table tblWordList(ID autonumber primary key, SearchString Text(200)) . Write Insert statement to add all the words to search e.g. Insert into tblWordList(SearchString) values('Apple') ; execute these queries in Access. OR you can open the table to add data , easier than insert statement.
Run the following query
Select * from tblVitalInfo where ObjectName in (Select SearchString tblWordList)
Related
I have a SELECT statement with a WHERE clause that uses a LIKE wildcard with an expression coming from a variable string that I have built using values from a table. However, although there are no errors, the query is not evaluating correctly to give the expected results, as it is returning all the results records and not applying the condition in the LIKE wildcard. The desired result should be fewer records returned as they will be filtered against the LIKE wildcard expression.
The variable I have built to use in the SQL query's LIKE wildcard is the following, along with the value of the string:
Declare #TrimmedAgeType Varchar(450);
The value is this: '%J%' AND PERM.AgeFilter NOT LIKE '%JS%'
The SQL query looks like this:
SELECT * FROM #MembershipInfo #PSP
INNER JOIN TRP_ME_PriceStructure PERM
ON #PSP.MembershipPriceStructurePK = PERM.MembershipPriceStructurePK
WHERE PERM.AgeFilter NOT LIKE + #TrimmedAgeType
When I hardcode the query with the string value below, I get the expected results returned back.
SELECT * FROM #MembershipInfo #PSP
INNER JOIN TRP_ME_PriceStructure PERM
ON #PSP.MembershipPriceStructurePK = PERM.MembershipPriceStructurePK
WHERE PERM.AgeFilter NOT LIKE + '%J%' AND PERM.AgeFilter NOT LIKE '%JS%'
If you want to know how I am initially building the string variable value, see below:
Declare #AgeType Varchar(450);
Declare #AgeReference varchar(450)
SET #AgeType = CONCAT(#AgeType, '''%' + #AgeReference + '%''') + ' AND PERM.AgeFilter NOT LIKE '
Additional Info:
This #AgeType variable is being generated inside a while loop
that is looping through a table of Age References. I later change the
name of the variable to #TrimmedAgeType as I do some additional work on it to remove the last
occurrence of ' AND PERM.AgeFilter NOT LIKE '
More Info:
I have a table of memberships with the AgeFilter column containing letter references ('A,U,J,C,JS', etc). I want to return all results that do not match the given references in the LIKE wildcard pattern. This is because the SELECT query is actually going to be a DELETE query and I will delete all records that are returned and do not match the given references in the LIKE wildcard pattern.
Hope someone can help. Thank you.
Let's say we have some filters stored here:
CREATE TABLE dbo.FilterPatterns
(
PatternID int PRIMARY KEY,
FilterPattern varchar(32) NOT NULL UNIQUE
);
To simulate the question, let's say we know the PatternID values we're after are 1 and 3:
INSERT dbo.FilterPatterns(PatternID, FilterPattern)
VALUES(1,'%J%'),(2,'%Q%'),(3,'%JS%');
We've got some members stored in a #temp table for reasons unknown (how is that populated?):
CREATE TABLE #MembershipInfo
(
MembershipPriceStructurePK int PRIMARY KEY
);
Let's insert a few rows to match and not match (note: 30 doesn't exist in the core table).
INSERT #MemberShipInfo VALUES(5),(10),(15),(20),(30);
Two of these will have matching age filters in the core table, the other two will not. We'll also add a row not in the temp table (25):
CREATE TABLE dbo.TRP_ME_PriceStructure
(
MembershipPriceStructurePK int PRIMARY KEY,
AgeFilter varchar(256)
);
INSERT dbo.TRP_ME_PriceStructure VALUES
(5,'foo'),(10,'BobJoined'),(15,'blat'),(20,'NodeJS'),(25,'funky');
Now our query can just do a NOT EXISTS against the filter patterns table using whatever logic you're currently using to pull values from that table to build the string:
SELECT * FROM #MembershipInfo #PSP
INNER JOIN dbo.TRP_ME_PriceStructure PERM
ON #PSP.MembershipPriceStructurePK = PERM.MembershipPriceStructurePK
WHERE NOT EXISTS
(SELECT 1 FROM
dbo.FilterPatterns AS fp
WHERE fp.PatternID IN (1,3)
AND PERM.AgeFilter LIKE fp.FilterPattern);
members 5 and 15 are returned
members 10 and 20 are left out because they matched the filter
members 25 and 30 are left out because they miss the join
Example db<>fiddle
Try to hard code the wildcard
SELECT * FROM #MembershipInfo #PSP
INNER JOIN TRP_ME_PriceStructure PERM
ON #PSP.MembershipPriceStructurePK =
PERM.MembershipPriceStructurePK
WHERE PERM.AgeFilter NOT LIKE + '%'+ #TrimmedAgeType + '%'
Using Dynamic SQL I have successfully written the query, returning me the expected results:
DECLARE #DeleteUnsuitableMemberships varchar(MAX)
SET #DeleteUnsuitableMemberships =
'DELETE #MembershipInfo FROM #MembershipInfo #PSP
INNER JOIN TRP_ME_PriceStructure PERM
ON #PSP.MembershipPriceStructurePK = PERM.MembershipPriceStructurePK
WHERE PERM.AgeFilter NOT LIKE ' + #TrimmedAgeType
EXEC(#DeleteUnsuitableMemberships)
I did was the following:
Declare a new variable.
Set that variable to the SQL query which I have wrapped in apostrophe (').
Appended the variable using the + operator.
Used the EXEC() function with the variable placed inside as a parameter.
The value of #TrimmedAgeType is still '%J%' AND PERM.AgeFilter NOT LIKE '%JS%'
Thank you all for helping.
Suppose I have a table containing a column by the name "Query". I have to display the records where the string in this column has used noloc instead of nolock. Note that noloc can be followed/preceded by ) or space etc. I just need all records that have anything before and after noloc except nolock. Is there a way to do it in SQL?
I tried:
select * from table1
where Query LIKE '%noloc%'
but this includes queries containing nolock. I tried variations of the above like putting space before and/or after % but none of them fills all the criteria.
You can use both conditions in the where clause
select * from table1
where Query LIKE '%noloc%' and Query NOT LIKE '%nolock%'
You want anything + noloc + any one char but k + anything. Here:
select * from table1
where Query LIKE '%noloc[^k]%'
The problem is I have a table with 4 columns. I have two search boxes.
Fields
FName
LName
Age
School
Text boxes
FName
School
If the user has inserted two values I want to get the intersect using both values. If only one value is present I want to have data using that value. I thought of not handling this in the application but with a stored procedure.
I thought of using IF ELSE in the stored procedure or having sub queries. But not a solid solution. I need some guidance to think of a possible way. Thank you in advance.
Here is what I have tried. This is just the query I need to embed this in a stored procedure
SELECT * FROM STUDENT WHERE FNname like '%TestFName%'
INTERSECT SELECT * FROM STUDENT WHERE School LIKE '%TestSchool';
If the 'TestSchool" becomes null it takes all the records which full fill the first query.
If both values are missing it returns the whole table.
If both values are there it returns the specific data tuples.
Pretty sure it is as simple as this.
SELECT *
FROM STUDENT
WHERE FNname like '%TestFName%'
AND School LIKE '%TestSchool%';
If use 'AND' rather than 'OR' it meets all the given conditions
SELECT *
FROM YourTable
WHERE (FName = #Fname OR #Fname = '')
AND (School = #School OR #School ='')
Here is the answer I came up for my own problem.
SELECT * FROM STUDENT WHERE FNname like '%TestFName%'
INTERSECT SELECT * FROM STUDENT WHERE School LIKE '%TestSchool';
In here if the 'TestFName" becomes null it takes all the records which full fill the second query.
If the 'TestSchool" becomes null it takes all the records which full fill the first query.
If both values are missing it returns the whole table.
If both values are there it returns the specific data tuples.
Thank you. If there is a better way than this, please enlighten us.
You can use this :
SELECT * FROM STUDENT WHERE isnull(FNname, '') like '%' + isnull(#FNname, '') + '%'
and isnull(School, '') like '%' + isnull(#School, '') + '%'
Use the parameters #FNname and #School in your stored procedure and use the above query in it.
I have to compare comma separated values with a column in the table and find out which values are not in database. [kind of master data validation]. Please have a look at the sample data below:
table data in database:
id name
1 abc
2 def
3 ghi
SQL part :
Here i am getting comma separated list like ('abc','def','ghi','xyz').
now xyz is invalid value, so i want to take that value and return it as output saying "invalid value".
It is possible if i split those value, take it in temp table, loop through each value and compare one by one.
but is there any other optimal way to do this ??
I'm sure if I got the question right, however, I would personally be trying to get to something like this:
SELECT
D.id,
CASE
WHEN B.Name IS NULL THEN D.name
ELSE "invalid value"
END
FROM
data AS D
INNER JOIN badNames B ON b.Name = d.Name
--as SQL is case insensitive, equal sign should work
There is one table with bad names or invalid values if You prefer. This can a temporary table as well - depending on usage (a black-listed words should be a table, ad hoc invalid values provided by a service should be temp table, etc.).
NOTE: The select above can be nested in a view, so the data remain as they were, yet you gain the correctness information. Otherwise I would create a cursor inside a function that would go through the select like the one above and alter the original data, if that is the goal...
It sounds like you just need a NOT EXISTS / LEFT JOIN, as in:
SELECT tmp.InvalidValue
FROM dbo.HopeThisIsNotAWhileBasedSplit(#CSVlist) tmp
WHERE NOT EXISTS (
SELECT *
FROM dbo.Table tbl
WHERE tbl.Field = tmp.InvalidValue
);
Of course, depending on the size of the CSV list coming in, the number of rows in the table you are checking, and the style of splitter you are using, it might be better to dump the CSV to a temp table first (as you mentioned doing in the question).
Try following query:
SELECT SplitedValues.name,
CASE WHEN YourTable.Id IS NULL THEN 'invalid value' ELSE NULL END AS Result
FROM SplitedValues
LEFT JOIN yourTable ON SplitedValues.name = YourTable.name
Just wanted to know if it was possible to do a pattern matching on a set of data from a table.
Like:
select * from Table where Column like any(select Pattern from PatternTable)
Note that the Pattern is always a substring of Column. Hence the use of like. Is it even possible to do this at a database level without the use of stored procedures?
If it helps, my RDBMS is MS SQL-Server
Edit:
Alright, I have a table containing a set of data like
PatternTable
____________
test1
test2
test3
test4
Now, a table Table has the following data:
Table
______
SomeDatatest4SomeData
SomeDataSomeData
Now, can I use a query as mentioned above to find a match: For the above query, this should return SomeDatatest4SomeData
You can do this using exists:
select *
from Table t
where exists (select 1
from PatternTable pt
where t.Column like pt.Pattern
);
SELECT t.*
FROM [Table] t
INNER JOIN PatternTable p ON t.[Column] LIKE '%' + p.Pattern + '%'