Select Into/Insert Into SQL Server query duplicates - mysql

Sorry for asking this question, but I am a beginner in SQL, my colleague at work build a view, which I need as datasource for a report, however since this view is based on several other views it takes like 45 minutes to execute the query. This is way to long. Therefore I created a table from that view, initial execution time is the same, but once in place it executes in seconds.
In Microsoft SQL Server 2014 I used the following query:
select *
into [dbo].[MAT_v_demnew_daily_am_all_data]
from [dbo].[v_demnew_daily_am]
This works fine, but since the view is updated daily I also need to refresh the table everyday. When I now execute the above mentioned query I get the message that the table already exists.
That's why I tried to use 'insert' in this case:
insert into [dbo].[MAT_v_demnew_daily_am_all_data]
select *
from [dbo].[v_demnew_daily_am]
Here I have the problem that it not only inserts the additional data but also the already existing data, so in the end I have duplicates.
As a workaround I now manually delete the [dbo].MAT_v_demnew_daily_am_all_data] table and then execute the select * into query.
Now I am looking for an easier solution, is it possible to having the table deleted by query and in the same query create a new one by select * into or is it possible to only insert new data from the view to the table so that I don't get duplicates.
Moreover, is it possible to have such SQL statement being executed automatically on a daily basis, maybe by .bat file and windows task scheduler?
I know that the source of all problems is the View and that we should improve that, but looking for a short term solution first.
Thanks so much.
Mathias

Try this:
IF OBJECT_ID('dbo.MAT_v_demnew_daily_am_all_data', 'U') IS NOT NULL
DROP TABLE dbo.MAT_v_demnew_daily_am_all_data
SELECT INTO dbo.MAT_v_demnew_daily_am_all_data FROM dbo.v_demnew_daily_am
This query is reusable on a daily basis.
You can create one stored procedure including this query.
Then you only need to execute the stored procedure.
Updated
Before you create the stored procedure, please check if you have the permission.
Then try:
create procedure [procedure_name]
as
IF OBJECT_ID('dbo.MAT_v_demnew_daily_am_all_data', 'U') IS NOT NULL
DROP TABLE dbo.MAT_v_demnew_daily_am_all_data
SELECT INTO dbo.MAT_v_demnew_daily_am_all_data FROM dbo.v_demnew_daily_am;
After you create it:
EXEC [procedure_name];

Related

How to execute procedure after time?

I have table Orders in Mysql, that contains orders.
Each order has some reviews in another table OrdersReviews.
How to execute procedure after specific time after creating order?
My logic is:
After adding order to table, fix added time and order id. Then tell procedure to launch after as sample: current time >order added time + 30`
Does Mysql support something like thatç like cron manager?
WAITFOR COMMAND
I think this is what you are looking for. The comand blocks the execution of the procedure for the time you want and then continues.
It is very useful because you shall combine it with triggers, other stored procedures and even set functions.
Here is the link, good luck.

How to combine 8 queries into one to create a procedure?

I have a table I created to match an online Template for uploading inventory to Amazon. In total, it has 440 columns. I'm not worried about that, and neither are they, it is mostly necessary. It pulls from two other tables that I'll call table1 and table2. I'll call the other one templateTable.
Basically, I'm starting with a TRUNCATE to completely wipe the information on the templateTable. I want it empty when it gets filled, for no reason other than it makes me feel comfortable. No other table gets truncated, just this table every time the query is run.
After that, there is a massive INSERT query that takes info from table1 and table2 and puts all of that into templateTable's specific columns.
Query 3 is an update at this point, and so is pretty much queries 3 - 8. They're all update queries. I did them separately from the second query, where everything gets populated, because each update has a CASE and different requirements.
I wanted to create a procedure for these queries so they could just run the one procedure and call it a day. But I'm uncertain how to combine the 8 queries that fill and correct the information in this templateTable. I should mention I'm not just taking info from one table and sticking it in the templateTable- it is more like "case when table1.modelNum = 1234 then templateTable.modelNum = 5678".
You can wrap all of your 8 SQL statements inside of a procedure in MySQL like this:
CREATE PROCEDURE MyProcedure()
BEGIN
<SQL STATEMENT 1>;
<SQL STATEMENT 2>;
<SQL STATEMENT 3>;
<SQL STATEMENT ...>;
END//
Then to call it you submit:
exec MyProcedure;

MySQL - Automate a view update

I'd like to know if it is possible to create an SQL function that will automatically update my View and add to it new tables in my DB.
My DB consist of multiple tables (same data structure) and are named as follow "MM_DD", now I would like to create a VIEW that joins all this data ( pretty simple , see query below) but I wish to automate the process so every time a new table is added the view will update.
CREATE OR REPLACE VIEW `viewTable` AS
select *,
md5(CONCAT(`columnA`,`columnB`)) AS myPK_id
from `05_06`
union all
select *,
md5(CONCAT(`columnA`,`columnB`)) AS myPK_id
from `05_08`
ect...
What I am doing at the moment is using PHP every time a table is added. It loops through the tables and create / update the view.
select * from information_schema.tables WHERE table_name LIKE '%05%'
Now that I have an array of table names -> create my Query string -> replace view...
Is this possible to do this in SQL?
If so, what is the correct approach?
Write a stored procedure to rebuild your view. You'll need to use what MySQL internally calls "prepared statements" so you can use string manipulation.
You'll still use your SELECT ... FROM information_schema.tables query to drive this stored procedure.
Once you get this working, you can embed it in a mySQL event, and arrange to run it automatically. For example, you could run it at the same time late at night.
Or, you can invoke the stored procedure immediately after you create one of these tables.

SQL Server : track table inserts

I have a table which get new data inserted every minute or so. According to the source code I have here, it is only done in one class which is not used anymore.
Is there any way to trace the inserts? What I mean is to see which queries they were inserted by, who sent those queries etc. As much info as possible.
I have tried several ways myself (e.g.sp_who2 'Active' stored procedure) without any success. I also have access to the machine running the SQL server and to the transaction backup files (.trn files) but have no idea how to open those files.
Add trigger to the table which follows inserts and insert to other table these variables:
getdate(),
host_name(),
App_Name(),
suser_sname()
Seems to me that this is enough
The trigger looks like this:
CREATE TRIGGER YourTrigger On YourTable
AFTER INSERT
AS
SET NOCOUNT ON;
INSERT logtable
SELECT APP_NAME(), HOST_NAME(), SUSER_SNAME(), GETDATE(), * FROM INSERTED
GO
OR
you can use Sql Server Profiler for catching the queries - it may be more flexible
You may use sp_depends like this:
sp_depends tablename
This only states information in the same database but it might say what you need!

Can I launch a trigger on select statement in mysql?

I am trying to run an INSERT statement on table X each time I SELECT any record from table Y is there anyway that I can accomplish that using MySQL only?
Something like triggers?
Short answer is No. Triggers are triggered with INSERT, UPDATE or DELETE.
Possible solution for this. rather rare scenario:
First, write some stored procedures
that do the SELECTs you want on
table X.
Then, restrict all users to use only
these stored procedures and do not
allow them to directly use SELECT on table
X.
Then alter the stored procedures to
also call a stored procedure that
performs the action you want
(INSERT or whatever).
Nope - you can't trigger on SELECT - you'll have to create a stored procedure (or any other type of logging facility - like a log file or what ever) that you implicitly call on any query statement - easier if you create a wrapper that calls your query, calls the logging and returns query results.
If you're trying to use table X to log the order of SELECT queries on table Y (a fairly common query-logging setup), you can simply reverse the order of operations and run the INSERT query first, then run your SELECT query.
That way, you don't need to worry about linking the two statements with a TRIGGER: if your server crashes between the two statements then you already logged what you care about with your first statement, and whether the SELECT query runs or fails has no impact on the underlying database.
If you're not logging queries, perhaps you're trying to use table Y as a task queue -- the situation I was struggling with that lead me to this thread -- and you want whichever session queries Y first to lock all other sessions out of the rows returned so you can perform some operations on the results and insert the output into table X. In that case, simply add some logging capabilities to table Y.
For example, you could add an "owner" column to Y, then tack the WHERE part of your SELECT query onto an UPDATE statement, run it, and then modify your SELECT query to only show the results that were claimed by your UPDATE:
UPDATE Y SET owner = 'me' WHERE task = 'new' AND owner IS NULL;
SELECT foo FROM Y WHERE task = 'new' AND owner = 'me';
...do some work on foo, then...
INSERT INTO X (output) VALUES ('awesomeness');
Again, the key is to log first, then query.