I'm using SQL Server 2008. I'm looking for a creative way to save and update a list of dates in our database.
I'm going to collect a list of dates from the application and I will need to check if each value already exists, if not add, and then delete any dates not in the list that are already stored in the database.
The easiest thing I can think of is to delete all dates associated to this particular request and then iterate over each item in my list and insert into database.
Does anyone have a more elegant idea?
You can use merge. You can also load the dates into a temporary table and do an insert such as:
with toinsert as (
select thedate
from #newdates nd left outer join
alldates ad
on nd.thedate = ad.thedate
where ad.thedate is null
)
insert into alldates(thedate)
select thedate
from toinsert
The toinsert alias uses a left outer join to do a "not in". I often find that this works better. Regardless of how you set up the queries (like this or with a merge), you should put in an index on the dates. It should make things go faster.
I would use a combination of table valued parameters and the NOT EXISTS function. So pass your dates from your application to a stored procedure as a paramater, the stored procedure will then return a list of all the dates inserted back to your application.#
The first step is to create the type so you can pass a list of dates to your procedure:
CREATE TYPE dbo.DateListType AS TABLE (Date DATETIME)
Next create your procedure. I have assumed you date table is called dbo.Dates, you'll obviously need to substitute your table in for this.
CREATE PROCEDURE dbo.InsertDates (#Dates dbo.DateListType READONLY)
AS
BEGIN
DECLARE #Inserted TABLE (Date DATETIME)
INSERT INTO dbo.Dates
OUTPUT inserted.Date INTO #Inserted
SELECT Date
FROM #Dates d
WHERE NOT EXISTS
( SELECT 1
FROM dbo.Dates
WHERE Dates.Date = d.Date
)
SELECT Date
FROM #Inserted
END
Not sure what your application is coded in so unfortunately can't suggest any code to call the procedure
Related
I am a Newbee using MySQL Workbench. I have a table Called requests. It has a column called STATUS and another called EXPIREDDATE. I want to create a Stored procedure that Inputs the text "Exipred" into the column STATUS if the date in EXPIREDDATE exceeds Todays date. The begining of the code is below. Thanks.
CREATE PROCEDURE `Add Expired` ( IF expireddate => todays date THEN status = "expired")
BEGIN
END
Inputs the text "Expired" in to a column A if the date in column B exceeds Todays date
You are describing an update statement with filtering:
update mytable set a = 'expired' where b > current_date
You can easily turn this to a stored procedure - although it wouldn't be very helpful (you can just run the query).
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
I have a table task, this table contains information of recurring tasks, fox example daily tasks, so I repeat each task because I want to know the result of each task over time
1/1/2014 Get Pizza OK
1/2/2014 Get Pizza OK
1/3/2014 Get Pizza Error
1/4/2014 Get Pizza OK
For this I made a stored procedure
DELIMITER $$
CREATE DEFINER=`db`#`%` PROCEDURE `SP_repeat_task`()
BEGIN
INSERT INTO Task
(
date_of_assignment,
Some fields
)
SELECT
DATE_ADD(tas.date_of_assignment, INTERVAL 1 DAY),
another fields
FROM Task tas
WHERE tas.date_of_assignment=CURRENT_DATE and many conditions
)
;
END
This procedure is invoked every day 5 minutes before midnight. And produces something like this
The problem is that I have to insert the id of the records added in another table
For example
When I add 4 tasks in insert-select statement i need add these to another table
In my case, there can be multiple records for each task.
I can easily obtain id_person in my select, but not how to use it in the next insert.
I cant change the structure of the tables, I have only my stored procedure to work
I read about mysqli_insert_id, but not how to use it in my case
EDIT
based in b.b3rn4rd answer
When i add the other field in cursor select
DECLARE records_to_clone_cursor CURSOR FOR
SELECT `field1`, `field2`, `field3` FROM `Task` WHERE ... ;
In FETCH return more rows because as there is a one to many relationship in my tables
so the query returns with old fields
DECLARE records_to_clone_cursor CURSOR FOR
SELECT `field1`, `field2` FROM `Task` WHERE ... ;
And i tried change the prepared statement for a classic Insert-Select
SET #NEW_ID = LAST_INSERT_ID();
INSERT INTO Another_table
(
id_task,
id_person
)
SELECT tas.id_task,
pe.id_person
FROM Task tas
INNER JOIN Person pe
ON pe.id_person = tas.id_assigned
WHERE tas.id_task= #NEW_ID;
-- EXECUTE insert_responables USING #NEW_ID, #Var_3;
But does nothing, first prepared works well, and Select-Inser work in nornal query.
that I can do?
EDIT 2
if I need to insert the values, but because they are different cause the cursor query returns more records and these are duplicated by the number of records in the field is_person
I have a table called table1 with three columns, one of which is Date_Of_Call which is of datetime type with the data in PDT. I basically need to convert the data from PDT to UTC and put the UTC converted dates into a new column in the existing table. I added a new column with:
alter table table1 ADD Date_Of_Call_UTC DATETIME;
I am able to get the proper time conversion with this select statement:
select CONVERT_TZ(Date_Of_Call, '-7:00', '-0:00') from table1;
The issue I am having is trying to use an update command to take the results of the select statement and put them in the new Date_Of_Call_UTC column. Any thoughts of how to do this?
I tried the below statement and a few variations but can't quite figure out what I need to do:
update table1 set table1.Date_Of_Call_UTC = (select CONVERT_TZ(Date_Of_Call, '-7:00', '-0:00') from table1);
Any assistance is appreciated!
this one should work:
update table1
set table1.Date_Of_Call_UTC = CONVERT_TZ(Date_Of_Call, '-7:00', '-0:00');
NOTE: dates are usually stored already as UTC in mysql, but during output they can be displayed with offset applied, read about it: http://dev.mysql.com/doc/refman/5.0/en/datetime.html and http://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html
Ok, First off, I am not a mysql guru. Second, I did search, but saw nothing relevant related to mysql, and since my DB knowledge is limited, guessing syntactical differences between two different Database types just isn't in the cards.
I am trying to determine if a particular value already exists in a table before inserting a row. I've decided to go about this using two Stored procedures. The first:
CREATE PROCEDURE `nExists` ( n VARCHAR(255) ) BEGIN
SELECT COUNT(*) FROM (SELECT * FROM Users WHERE username=n) as T;
END
And The Second:
CREATE PROCEDURE `createUser` ( n VARCHAR(255) ) BEGIN
IF (nExists(n) = 0) THEN
INSERT INTO Users...
END IF;
END
So, as you can see, I'm attempting to call nExists from createUser. I get the error that no Function exists with the name nExists...because it's a stored procedure. I'm not clear on what the difference is, or why such a difference would be necessary, but I'm a Java dev, so maybe I'm missing some grand DB-related concept here.
Could you guys help me out by any chance?
Thanks
I'm not sure how it helped you, but...
why SELECT COUNT(*) FROM (SELECT * FROM Users WHERE username=n) and not just SELECT COUNT(*) FROM Users WHERE username=n?
Just make the user name (or whatever the primary application index is) a UNIQUE index and then there is no need to test: Just try to insert a new record. If it already exists, handle the error. If it succeeds, all is well.
It can (and should) all be one stored procedure.