insert record when datetime = system time - sql-server

I am new to sql so bear with me. I want to insert a record into another table when a datetime column = the system time. I know this is an infinite loop. I am not sure any other way to handle what I am trying to solve.
INSERT INTO dbo.Que
(Name, Time)
SELECT ProspectName, ProspectDate
FROM myProspects where ProspectDate = CURRENT_TIMESTAMP
I need to place a phone call at a certain time. I need to insert the record into another table to execute the call when the time = now. If you have a better way of handling this, please tell me.
Thanks

If you are using sql server, you can use the getdate() function.
You would need to insert the createdate into a column of the call on insert, also using getdate() or if using .net System.Datetime.Now
e.g. select all calls that happened in the last x amount of time in SQL server:
select * from calls where createdate > getdate() - .1

Related

SQL DateTime Inserted Incorrectly From VB.NET

Have a table I'm logging information from a .NET program into.
The VB.NET app explicity dictates the format of the DATETIME string like below
responsedt = Date.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")
I then pass this into an INSERT statement that updates my table, however even though the entire setup of the SQL Server is en-GB (British English) the DateTime has gone in the following format:
2019-09-05 19:09:34.823
This was done yesterday so actually should be
2019-05-09 19:09:34.823
The day and month should be switched around, I have tried performing an update on the table post process to get it to update using the following code
FORMAT (xa.daterequested, 'yyyy-dd-MM HH:MM:ss.fff', 'en-gb')
How while this works in a SELECT statement it doesn't seem to work when I do the UPDATE statement.
It is not ideal to have to update all the records dates after the initial INSERT so a solution to either the .NET side of the issue or the SQL would be appreciated as its pickling my head.
You have 2 options to prevent the error from happening again:
Keep dates as date/time data types instead of converting them to strings.
Use formats that are not language or settings dependent. In SQL Server these would be YYYYMMDD hh:mm:ss.msss OR YYYY-MM-DDThh:mm:ss.mss (notice the T between date and time)
To correct the dates already inserted you could use the format codes in the CONVERT function.
UPDATE t SET
daterequested = STUFF( STUFF( StringDate, 5, 0, SUBSTRING(StringDate,7,2)), 9, 2, '')
FROM YourTable t
CROSS APPLY( SELECT CONVERT( varchar(25), '20190905 19:09:34.823', 121) AS StringDate) AS x;

Is there a way I can make an ASP.NET MVC web app execute queries on SQL Server when a date column in a table <= current date

My question is a mess, but what I mean is basically this: let's say I have a table called EXECUTELATER (in my SQL Server database for my app) and I have a column called DATE. I want to execute queries every time a row/rows in that table has DATE <= current system time, do something with the data, put some data in another table and delete this row from the table EXECUTELATER.
One thing in my mind is to create another simple app logged with another user to query every millisecond and check if there is a DATE matching, but that sounds absurd.
Is there a way I can do this within the web app? Can anyone suggest me a smart way I can make this work? I don't mind if I have to work with full SQL date format or store the date in long type, work with the web app, create a new application for that use, use something in SQL Server itself or whatever.
Again sorry for the badly structured question, I'm not sure how to put this together. Thank you for checking!
you can use triggers like :
create TRIGGER [dbo].[TrgX]
ON [dbo].[EXECUTELATER]
AFTER UPDATE,insert
AS
BEGIN
SET NOCOUNT ON;
update [dbo].[tblx]
set [columnx] = x
from inserted i
inner join [dbo].[tblx] p on i.[Relatedcoulumn] = p.Relatedcoulumn
where i.[Date] >= getdate()
END

Update is being executed before BulkInsert

I wrote a program to insert some records using sqlCopy for faster processing, and then the code executes and update statement [on an other table] based on the newly inserted records.
Problem is that the update almost always executes before the insert! [about 2 seconds before.. according to the time-stamps of the insert and update rows.] the only way I could make the update execute after the insert is to put the code asleep for 2-3 seconds.. Is there a better way to make sure the insert completes before the code continues?
I even captured the RowsCopied event, the rows are instantly copied 'before' the update. but in the database the update gets in earlier.
bulkCopy.WriteToServer(table)
Dim Sql = "Update tbl Set Total = (select sum(qty) from Inserttbl where inId = ID)"
ExecuteSQL(Sql)
Found the problem... the insert timestamp was provided by the client, while the update timestamp came from the server. The clients time is 2 seconds earlier then the servers time..
I changed both should use the servers getDate function. problem solved.

Simulate current date on a SQL Server instance?

Is it possible to change the datetime for a particular database on SQL Server?
Is it tied to the operating system's date/time?
We wish to simulate a future datetime for testing purposes i.e. so the GETDATE() returns a date in the future.
It's got to be in a semi-production (staging) environment so unfortunately changing the OS date / time isn't an option for us.
In an ideal world we'd spin up a virtual server, but also not really an option at the moment.
As stated, by others, No.
A really hacky workaround, would be be to write your own function to return the date you want and have it return GETDATE() when you're done testing, and call that function instead. There's probably some slight overhead in doing this, but it'll do what you need.
Unfortunately it is tied to the OS date and time. See here: http://msdn.microsoft.com/en-us/library/ms188383.aspx
This value is derived from the operating system of the computer on
which the instance of SQL Server is running.
You can always use this and adjust accordingly:
SELECT getutcdate()
Please see below for more information
StackOverflow Question
But there is no way to change the results from a GETDATE() without changing the server's date.
Added:
You could do a EXEC xp_cmdshell 'DATE 10/10/2011' if you wish... but it's not advised.
Another workaround I've had some success with is to add an INSTEAD OF trigger to any table where a GETDATE() value is being inserted and modify it there e.g.:
ALTER TRIGGER [dbo].[AccountsPayableReceivable_trg_i] ON [dbo].[AccountsPayableReceivable]
INSTEAD OF INSERT
AS
SET NOCOUNT ON
SELECT *
INTO #tmp_ins_AccountsPayableReceivable
FROM INSERTED
UPDATE #tmp_ins_AccountsPayableReceivable
SET dtPaymentMade = '01-Jan-1900'
WHERE dtPaymentMade between dateadd(ss, -5, getdate()) and dateadd(ss, +5, getdate())
INSERT INTO AccountsPayableReceivable
SELECT *
from #tmp_ins_AccountsPayableReceivable
(Incidentally, the where clause is there because my test script autogenerates these triggers, adding an update for every datetime column, so I only want to update those that look like they are being inserted with a GETDATE() value.)
I believe you can create a user function that would do the calculation for you and apply that.
http://msdn.microsoft.com/en-us/library/ms186755.aspx
Also, it can be used as the default value for a column.
Bind a column default value to a function in SQL 2005

How to alter a DateTime field when it is updated?

Is there a database level function (trigger or something) that I can use to alter a DateTime field when new data is inserted? The issue is that a service I am integrating with happens to send out all of its times (in this case the time some info was received on their end) in GMT.
I need to automatically change this to reflect the time in the timezone the db server is in. For example, if they send me 2:34 PM, but I am in NYC, I would want it to be entered in the db as 9:34 AM. This would also have to account for differences in Daylight Savings between GMT and wherever the server is, which seems like a nightmare. Any suggestions?
Also, I am using SQL Server 2005 if that helps.
EDIT:
Let me clarify one thing. The dates going into this column are retrieved in batches every so often (5, 10, 15 minutes), so I think the only way to go is to alter the time once it has been received, not to add a TimeModified field or something. Is that even feasible?
You could create
a default value for the DateTime which gets set when you insert a new record
CREATE TABLE dbo.YourTable
( ........,
LastModifiedOn DATETIME
CONSTRAINT DF_YourTable_LastModifiedOn DEFAULT (GETDATE())
)
a AFTER UPDATE TRIGGER which sets the DateTime field to the new value whenever you've updated your row
CREATE TRIGGER trgAfterUpdate
ON dbo.YourTable
AFTER UPDATE
AS BEGIN
UPDATE dbo.YourTable
SET LastModifiedOn = GETDATE()
FROM INSERTED i
WHERE i.Table1ID = YourTable.Table1ID
END
With the default value and the trigger, your datetime field LastModifiedOn should always be up to date and showing the last modification date/time.
Marc
Another option here would be to use a calendar table where you map a UTC date and time to the local date and time value.
Disadvantages here are a loss in some of the granularity. If seconds are important I would not implement this; you can look at the size of the calendar record and compare it to the size of storing a datetime for every record in your transactional table. Obviously the smaller the volume the less beneficial this solution will be. Also, if you don't build in automatic and unattended repopulating future records in the solution the table will "run out" of records, and you will have left a time bomb for whoever comes in after you (maybe yourself too).
Advantages though are that you will be able to perform any queries on this table much more quickly (because it is an integer). Also if you ever decide that your NYC server needs to move to Sacramento, you can update the "localDateTime" and leave the UTC time in tact.
Table structure (granularity will be up to your needs):
ID int
utc_month int
utc_day int
utc_year int
utc_hour int
utc_minute int
local_month int
local_day int
local_year int
local_hour int
local_minute int
Yet another option (again depending on volume) is to deploy a managed assembly.
(see this site for instructions, you do have to make a server configuration change. How to implement a managed udf or sp)
Here is the C# that I put in my udf
public static SqlDateTime udf_ConvertUTCDateTime(SqlDateTime utcDateTime)
{
DateTime dt = utcDateTime.Value;
utcDateTime = dt.ToLocalTime();
return utcDateTime;
}
The following code will return you the converted UTC datetime. Just use that value in your insert or trigger.
Declare #D datetime
set #D = GetUTCDate()
select #D
select dbo.udf_ConvertUTCDateTime(#D)
Create a field of the type Timestamp - that will get updated whenever any data is modified in that row. Alas, it's literally a relative timestamp, so it can only be used for versioning. More information can be found here:
http://msdn.microsoft.com/en-us/library/ms182776(SQL.90).aspx
following example should do the job. Add ModifiedOn or similar DateTime field to your db table.
insert into foo (field1, field2, ...., ModifiedOn)
values (value1, value2,...., GetDate())
or for update
update Foo
set field1 = value1,
field2 = value2,
.
.
.
.,
ModifiedOn = GetDate()
Where ....

Resources