Select field on multiple values - sql

I am currently trying to create a query where i want to select rows if one field contains multiple values. I think ill just give you an example:
Database: field="Ground;Lava;Rocks"
Query should be: select where field contains "Ground" and "Rocks".
My first attempt would have been:
SELECT * FROM TerrainLayer WHERE tags LIKE '%Ground%' AND tags LIKE '%Rocks%';
Would this be an acceptable solution or are the better (more efficient) ways to achieve this? Thank you in advance for your help.

Something like this should also work, and if you have multiple LIKE clauses should be a little more efficient:
SQL
CREATE TABLE #SearchItem (Search varchar(255))
INSERT INTO #SearchItem VALUES
('Ground'),
('Rocks'),
('Whatever')
SELECT *
FROM TerrainLayer as t
JOIN #SearchItem as s
ON t.tags COLLATE DATABASE_DEFAULT LIKE '% ' + s.Search + ' %'
For SQLite
CREATE TABLE SearchItem (Search varchar(255))
INSERT INTO SearchItem VALUES
('Ground'),
('Rocks'),
('Whatever')
SELECT *
FROM TerrainLayer as t
JOIN #SearchItem as s
ON t.tags LIKE '% ' + s.Search + ' %'
From what I tested a JOIN like this will be quicker. Obviously, you wouldn't need to manually populate the #SearchItem table like this.

try this:
SELECT * FROM TerrainLayer WHERE tags LIKE '%Ground%Rocks%';

Related

Is there a way I create a SQL view of multiple tables based on a query of the table schema?

I have a SQL database where there are multiple tables maintained by other people which I would like to join up to create a view. The trouble is the number of tables keeps expanding! The columns and character lengths are the same.
I can get as far as creating a list of the tables by using
SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE 'Table%'.
At the moment I have a union all query like the below
SELECT * FROM table1
UNION ALL
SELECT * FROM table2;
but the table list keeps growing. Is there any I can create something to loop thought the tables? Something like
*SELECT * FROM (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE 'Table%') UNION ALL*
I know that wouldn't work but I'm hoping there's some sort of trick to get to go all the way! This is on SQL Server 2012 if that helps.
Thanks
declare #s nvarchar(max);
set #s=''
select
#s=#s +'(select * from [' + s.name + '])'+
case when ROW_NUMBER() over (order by s.name) != count(*) over ()
then
' UNION ALL '
else
''
end
from
sys.tables as s
where s.name like 't%'
print #s;
There is a bit more to think about, you need to make sure the field counts are the same before hand also to be on the safe side, may be best to avoid select * and use field names that you require. This should produce the SQL statement to run in a stored proc as detailed in the comments. Spend some time error trapping this and doing neccessary checks for continuity in the field names as mentioned.

Database query with two fields in the same table. Don't consider if any of the values are empty

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.

SQL: Correctly identify and correct(if possible) names in database

I have a large database of names, and I'm hoping to identify incorrect capitalization.
Right now I'm using the following...
SELECT *
FROM myTable
WHERE LastName LIKE '%Mcd%' COLLATE SQL_Latin1_General_Cp1_CS_AS
Now of course this is inefficent because I have to run/edit this over and over for different cases. My thinking is find a list of name cases that would provide possible problems, and do
LIKE IN ('case1','case2','case3','case4', ...)
if that's possible. Is there another way that I'm not thinking of?
Other cases I'm thinking I'll have to check are abbreviations (%.%), hypens (%-%), and apostrophes (%'%).
You could use
SELECT *
FROM myTable
WHERE LastName LIKE '%Mcd%' or LastName LIKE '%Foo%'
Or
WITH T(Word) AS
(
SELECT 'Mcd' UNION ALL
SELECT 'Foo'
)
SELECT *
FROM myTable
JOIN T ON LastName LIKE '%' + Word + '%'
To avoid needing to scan myTable multiple times.
To avoid processing the string multiple times you could use CLR and Regular Expressions.

sql searching multiple words in a string

What is the most efficient and elegant SQL query looking for a string containing the words "David", "Moses" and "Robi". Assume the table is named T and the column C.
Select * from table where
columnname like'%David%' and
columnname like '%Moses%' and columnname like'%Robi%'
In SQL Server 2005+ with Full-Text indexing switched on, I'd do the following:
SELECT *
FROM T
WHERE CONTAINS(C, '"David" OR "Robi" OR "Moses"');
If you wanted your search to bring back results where the result is prefixed with David, Robi or Moses you could do:
SELECT *
FROM T
WHERE CONTAINS(C, '"David*" OR "Robi*" OR "Moses*"');
Here is what I uses to search for multiple words in multiple columns - SQL server
Hope my answer help someone :) Thanks
declare #searchTrm varchar(MAX)='one two three ddd 20 30 comment';
--select value from STRING_SPLIT(#searchTrm, ' ') where trim(value)<>''
select * from Bols
WHERE EXISTS (SELECT value
FROM STRING_SPLIT(#searchTrm, ' ')
WHERE
trim(value)<>''
and(
BolNumber like '%'+ value+'%'
or UserComment like '%'+ value+'%'
or RequesterId like '%'+ value+'%' )
)
If you care about the sequence of the terms, you may consider using a syntax like
select * from T where C like'%David%Moses%Robi%'
Oracle SQL :
select *
from MY_TABLE
where REGEXP_LIKE (company , 'Microsodt industry | goglge auto car | oracles database')
company - is the database column name.
results - this SQL will show you if company column rows contain one of those companies (OR phrase)
please note that : no wild characters are needed, it's built in.
more info at : http://www.techonthenet.com/oracle/regexp_like.php
if you put all the searched words in a temporaray table say #tmp and column col1, then you could try this:
Select * from T where C like (Select '%'+col1+'%' from #temp);
Maybe EXISTS can help.
and exists (select 1 from #DocumentNames where pcd.Name like DocName+'%' or CD.DocumentName like DocName+'%')
Oracle SQL:
There is the "IN" Operator in Oracle SQL which can be used for that:
select
namet.customerfirstname, addrt.city, addrt.postalcode
from schemax.nametable namet
join schemax.addresstable addrt on addrt.adtid = namet.natadtid
where namet.customerfirstname in ('David', 'Moses', 'Robi');

MySQL: JOIN two tables on LIKE

I have a table with a column containing text, and I want to select all of the tables where the text from one of the rows in a second table appears in that row. Here is a pseudo-query:
SELECT title FROM recipes AS r
JOIN ingredients AS i
ON r.ingredients LIKE '%' + i.name + '%';
The above query does not work, however. How do I do this correctly?
SELECT title
FROM recipes r JOIN ingredients i ON r.ingredients LIKE concat('%', i.name, '%')
MySQL is weird, and makes you use the concat operator to concatenate strings together. Most others use ||
You can't concatenate strings with the + operator (it's for arithmetic only). Use concat('%',i.name,'%') instead.