Select From Multiple and New Tables will be created - sql

My Simple Query is
SELECT MAX(DATETIME)
FROM gss.dbo.contacts_23
WHERE Identification = ''
GROUP BY Identification
How can I select Max(date) from 25 tables and new tables can be created?
These tables like (contacts_22,contacts_25,contacts_29,contacts_36,.. and the new)
I tried to think as following
use union but what about the new tables will be created next time
select all tables start with 'contacts_' to fetch all these tables and the tables will be created next time
SELECT TABLE_NAME
FROM GSS.INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME like 'contacts_%'
but it's not doable with FROM clause
How can I do that GET MAX(DATE) FROM .... AND NEW TABLES
I'm using SQL Server 2012
Thanks in advance

The data model is horrible, and there is no clean way of achieving what you want.
The first way is to create a view which unions all your contacts_ tables, and then to run your query on that view.
Create view contacts_view as
select * from contacts_20
union
select * from contacts_21
...
This is the simplest solution, but only works if you can be certain that you're not creating more tables which need to be included in the view.
The alternative is to use dynamic SQL. This would use your query on the schema database to construct a SQL statement, which you then execute. This can get moderately complex, and is generally hard to test and debug, but does allow new tables to be automatically included in the results.

Related

Do a select query on all tables of PostgreSQL database using pgAdmin 4

I have a database of around 90 schemas. In each of these schemas, I go to "Materialized Views" and go to a one of the views called, "product_visitor_view" and I create a SELECT script and I write this script and run it and see the results:
SELECT priority, count(*)
FROM ag_modem_01.product_visitor_view
group by priority;
However, I cannot do this for all 90 around schemas. Is there a way I can do this for all schemas and the results would be shown for each schema in a page and how can I do this?
Thank you in advance.
You can prepare the SQL for each schema using below query.
The idea is to instead of manually writing all the query, you can use the system table pg_matviews which contains information about materialized views.
Once you have the list, just need to do union all between all the rows.
select
string_agg('select '''||schemaname||''' as schema,priority,count(*) from '||schemaname||'.'||matviewname
||' group by priority '||chr(10),' Union All '||chr(10)
)
from pg_matviews
where matviewname='product_visitor_view'
and ispopulated=true; -- to filter out Views which has not been populated
Take the output from this query and run it in the Querytool.

Rename all tables in SELECT query

Can anyone tell me how to replace the name of all the table names in a the SELECT/FROM statements?. I'm looking of a way that works well across vanilla queries as well as more complex ones with sub-queries and joins.
I.e.
New table name: new_table
Original query: SELECT * from table;
Result query: SELECT * FROM new_table;
Thanks a lot,
j
If your queries are as simple as what you're proposing, you should be able start by parsing the query which will give you a SqlSelect object. From there you can use getFrom to check if it's the table you want to change and setFrom to change it.
If you want to handle more complex queries, you should be able to implement the SqlVisitor interface to find all occurrences of the table to replace.

Run two select statements in one view?

I have some SQL that is broken into two SELECT statements. The first SELECT statement inserts results INTO a temp table. The second SELECT statement is a COALESCE that reads data from the temp table the first one inserted data into. I need to be able to run these together (one after the other) and unfortunately cannot put these into a Stored Procedure due to the old reporting tool my company uses. The reporting tool must read from a VIEW or a TABLE. I wanted to put these into a VIEW, but have researched that a view cannot have more than one SELECT. Any ideas and examples on how to accomplish this? My original post/solution showing the SQL is in this post.
The temp table select could be converted to be a CTE (With clause), and the 2nd part the select query of the view.
Alternatively you could just inline it with sub-selects, but depending on complexity that might make it harder to maintain.
CREATE VIEW yourView AS
WITH myFirstSelect(someFields) AS
(
SELECT somefields FROM sometable
)
SELECT * from myFirstSelect
Docs : https://learn.microsoft.com/en-us/sql/t-sql/queries/with-common-table-expression-transact-sql?view=sql-server-2017

SQL querying multiple schemas

I am looking to run a query on several schemas in workbench. bascially, they are all symmetric , just different dates. In workbench, i can only select one of them and run the query. Is there a way to aggregate them and run the query over a selection of schemas?
EDIT:
To elaborate a bit more, I have schemas with names yyyy_mm_dd for each day. Ideally, instead of doing a union over them as suggested by Guish below, If would like a dynamic query that would be able to turn the name of the schema into a valid date and Union all of them where the date is within a defined range. Is this possible? I am using Oracle and sql workbench
I guess you are using mySql workbench.
Use an union operator.
(SELECT a FROM `schema1`.`t1` )
UNION
(SELECT a FROM `schema2`.`t1`);
Info here
You can then create a view from your query.
A thread here on querying multiple shema
In know Transact-SQL a lot more and it is similar.
SELECT ProductModelID, Name
FROM Schema1.ProductModel
UNION ALL
SELECT ProductModelID, Name
FROM Schema2.ProductModel
ORDER BY Name;

Rails - Get latest entries from multiple tables

I am using RoR for app development and want to implement the following:
For the app's RSS feed I need to pull out 10 latest entries from the database. The part I am not able to figure out is how to get last 10 entries across multiple tables.
Pulling last n records from a single database table is easy but how to pull last n records across multiple database tables.
Any suggestions?
There are none built-in methods in ActiveRecord for this, doing this in SQL very simple You just do UNION.
SELECT * FROM (
SELECT table1.*, 'table_1_type' AS table_type FROM table1
UNION ALL SELECT table2.*, 'table_2_type' AS table_type FROM table2
UNION SELECT table3.*, 'table_3_type' AS table_type FROM table3
) AS my_union ORDER created_at DESC LIMIT 10;
This query will return 10 rows, each row will have tables from each of those. I suggest You to create plain Ruby class that executes this raw query and rebuilds the objects.
Or even better just fetch the values necessary for You and represent them using plain Ruby classes (not using You models).
You can access postgres connection through any AR class, like this MyModelClass.connection
Example of using raw connection:
conn = MyModelClass.connection
res = conn.exec('select tablename, tableowner from pg_tables')
res.each do |row|
row.each do |column|
puts column
end
end
In same fashion You can execute Your query and populate Ruby objects.
UPD
There is also a third option You can use. Create a new model RssItem and back it with SQL view instead of table. The approach is explained in this post:
http://hashrocket.com/blog/posts/sql-views-and-activerecord
Is there a particular reason you want to combine queries for multiple tables into one sql query? I don't think its possible to do a union query.
You can try something like this, its not exactly what you want though:
#all_items = [#record_videos.all, #musics.all, #new_topics.all].flatten.sort_by{ |thing| thing.created_at}
taken from:
rails 3 merge multiple queries from different tables
If it is important to you then the true way to accomplish this in Rails is to use STI (single table inheritance). But that would require restructuring your DB and models.