Delete/Create View Every Time Insert Is Done - sql-server-2008

Is it possible that each time a table has a record inserted, delete a view, then re-create a view using the data in the table. For example, my table structure is like such
Create Table NeedView (
Databasename varchar(100)
,DateAdded datetime
)
And the information in that table is just a fully qualified database name like so servername.database.dbo.table My thought is to have a trigger applied that each time a record is inserted into this table, 1st drop the view (it would be called dbo.ViewMaster then recreate it with a quick select of
Select fullname, phone
from each table in the database. Is this achievable through a trigger?
EDIT
I now just need to figure out how to cycle the table to create a view for each databasename in the table...I have this rough syntax ready, with the exception of actually iterating each database. Can someone help me with the missing piece?
CREATE TRIGGER GetViewReady ON [FullOn]
FOR INSERT
AS
IF OBJECT_ID('FullInformation', 'V') IS NOT NULL
DROP VIEW FullInformation
Declare #database varchar(100), #campaignID varchar(10)
Declare C1 Cursor FOR
Select database
FROM [FullOn]
Open C1
Fetch Next FROM C1 INTO #database
WHILE ##Fetch_Status = 0
Begin
'Here is where the actual iteration to create the view would go...
'How would that statement actually need to be syntactically written?
Fetch Next From C1 Into #database
End
GO
EDIT --
A few database names would be hellfire.master.dbo.hennigar, hellfire.mainframe.dbo.dekalb, hellfire.master.dbo.ftworth and the syntax I am after would be like so:
Select fullname, phone
FROM hellfire.master.dbo.hennigar
UNION ALL
select fullname, phone
from hellfire.mainframe.dbo.dekalb
UNION ALL
select fullname, phone
from hellfire.master.dbo.ftworth

Related

mysql insert into table if exists

In my project I have two code paths that interact with MySQL during first time setup. The first step is the database structure creation, in here, a user has the ability to pick and choose the features they want - and some tables may not end up being created in the database depending on what the user selects.
In the second part, I need to preload the tables that did get created with some basic data - how could I go about inserting rows into these tables, only if the table exists?
I know of IF NOT EXISTS but as far as I know, that only works with creating tables, I am trying to do something like this
INSERT INTO table_a ( `key`, `value` ) VALUES ( "", "" ) IF EXISTS table_a;
This is loaded through a file that contains a lot of entries, so letting it throw an error when the table does not exist is not an option.
IF (SELECT count(*)FROM information_schema.tables WHERE table_schema ='databasename'AND table_name ='tablename') > 0
THEN
INSERT statement
END IF
Use information schema to check existence if table
If you know that a particular table does exist with at least 1 record (or you can create a dummy table with just a single record) then you can do a conditional insert this way without a stored procedure.
INSERT INTO table_a (`key`, `value`)
SELECT "", "" FROM known_table
WHERE EXISTS (SELECT *
FROM information_schema.TABLES
WHERE (TABLE_SCHEMA = 'your_db_name') AND (TABLE_NAME = 'table_a')) LIMIT 1;

INSERT data based on IF EXIST

I'm building a system update feature for a client of mine, the client drags and drops a xls sheet (export form SAP) and that query basically TRUNCATES the existing "project data" in the import_table and inserts all project data from the xls, now that works fine, but what I need help with is writing a stored procedure that selects the project_number from the import_table and checks if that project_number already exists in the project_table, and if it doesn't exist then INSERT the new project data from import_table by project_number.
So far what I have:
CREATE PROCEDURE `update_projects` ()
CREATE DEFINER=`root`#`%` PROCEDURE `update_projects`()
BEGIN
INSERT INTO `permit`.`project2`(project,description,mat,city,stat,own,est_start,est_end,constr_start,constr_end,constr_cnf,plan_order,div_code,div_long,constr_total_plan,constr_total_act)
SELECT OrderNo,OrderDescription,mat,MainWorkCtr,OrdUsrStatus,JobOwner,ESTStartDate,ESTEndDate,ConstrStartDate,ConstrEndDate,ConstrCNFDate,PlanningOrder,division,division_long,cons_total_plan_hrs,cons_total_act_hrs
FROM `permit`.`wrm100_raw` i
WHERE NOT EXISTS (SELECT 1 FROM `permit`.`project2` pt WHERE i.OrderNo = pt.project)
END;
If I understand correctly, then you can do the check using a WHERE clause:
CREATE DEFINER=`root`#`%` PROCEDURE `update_projects`()
BEGIN
INSERT INTO `db`.`project_table` (project_table columns...)
SELECT import_table columns...
FROM db.import_table i
WHERE NOT EXISTS (SELECT 1
FROM db.project_table pt
WHERE i.project_number = pt.project_number
)
END;
If the concern is duplicated project_numbers, then you should define a unique constraint/index and let the database validate the data.

How to automatic truncate table in MySQL every 3 months?

I have a PHP/MySQL project having 15 tables. One of table name tbl_user_log, where all user log will saved. I want to empty or truncate this table in every 3 month.How could I do this using trigger or any solution is applicable.
You can set a cronjob to a certain route of your project to perform following sql:
DELETE FROM tbl_user_log
See this website: http://setcronjob.com
Or you can simply use mysql EVENTs.
It may helps you
declare #tbl nvarchar(max)='table_name'
if (
(select create_date FROM
sys.tables where name=#tbl)
<= (SELECT DATEADD(month,-3, GETDATE()))
begin
truncate table #tbl
end
else
select 'table creation date is not more than 3 months'
better you can put this in a procedure and u can directly pass table name as input and can wrk efficently

How to save records from one table to another table using stored procedure in mysql?

I have tried, but I don't know how to do this.
I want to migrate records from one table into another table using a stored procedure. I have started with a simple procedure (not sure whether it is right or wrong) to print the records based on some condition. Here is the code with which i have tried:
CREATE PROCEDURE curdemo()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE a VARCHARCHAR(16);
DECLARE cur1 CURSOR FOR SELECT user_name FROM discovery_configuration;
OPEN cur1;
REPEAT
FETCH cur1 INTO a;
IF a!=' ' THEN
select a;
END IF;
END REPEAT;
CLOSE cur1;
END;
I need a stored procedure to migrate those records to another table if user_name column is empty. Can anyone guide me?
Why does it have to be a stored procedure?
You can copy the records in one query, then delete them with another.
Copy to another table where user_name is empty:
INSERT INTO other_table (id, user_name, other)
SELECT (id, user_name, other)
FROM discovery_configuration
WHERE user_name IS NULL OR TRIM(user_name) = '';
Then, after you have copied these records, delete from original table:
DELETE FROM discovery_configuration WHERE id IN (SELECT id FROM other_table);
Are you inserting all the columns or only user name? if you are inserting all the columns into the another table you should be getting all the columns into the cursor and then insert into the table.. and leave this..based on the info provided above i got that you would like to migrate the data from one table to another table if the username column is null...right?
then you have an easy way to do that.
INSERT INTO A (COUMNS DETAILS) SELECT COLUMNS FROM B WHERE B.USERNAME = ' ';
Try this and let me know..!!
-Rajesh Uddem
How about:
Insert userName into newTable
Select userName from discovery_configuration where cur1 != ' '

#temporary table Microsoft SQL seems to get lost

I have a little exercise where I need to access data from a view and print it out in a report. I have created a #temporary table to store the data in and the to retrieve it and display it in the report by using a while loop.
Problem is the temporary table seems to go 'missing'.
--Creating my report
USE PetShopDataBase
CREATE PROCEDURE spPetShopReport
#customerID INT
SELECT *
INTO #temporary
FROM vwPetshop
WHERE customerID = #customerID
GO
ALTER TABLE #temporary
ADD Printed SMALLINT
GO
Then from this point the object is regarded as invalid
UPDATE #temporary
SET Printed = 0
GO
the error message I get when I run the code is
Msg 4902, Level 16, State 1, Line 2
Cannot find the object "#temporary" because it does not exist or you do not have
permissions.
Why is that?
Kind regdards
Do not use GO inside of a stored proc. Go ends the batch and thus the stored proc.
BTW way all of this code can be compressed into one statement
SELECT * INTO #temporary
FROM vwPetshop
WHERE customerID = #customerID
ALTER TABLE #temporary
ADD Printed SMALLINT
UPDATE #temporary
SET Printed = 0
try this instead:
SELECT *, CAST(0 AS SMALLINT) AS Printed
INTO #temporary
FROM vwPetshop
WHERE customerID = #customerID
You can use global temporary table in this case (just two ## instead of one #)..
SELECT *
INTO ##temporary
FROM vwPetshop
WHERE customerID = #customerID
Local temporary tables are not visible outside procedure in which it was created..