I have a datetime column in sql2005. it's default value is getdate().
How can I update it's value automatically when others value update?
Use a trigger on the table!
CREATE TRIGGER updateDate
ON dbo.Table
AFTER UPDATE
AS
UPDATE Table
SET ModifiedDate = GetDate() -- or sysdatetimeoffset()
where table.Id = inserted.Id
You can use timestamp variable, basicly it updates itself everytime the row is changed and you can have only one timestamp variable per specific table.
Take a look at:
http://msdn.microsoft.com/en-us/library/aa260631(SQL.80).aspx
You can make a trigger for this, but depending on how often you update it could be cumbersome.
Are most of your updates batch updates or individual records? Is it ad-hoc or done through a stored proc? If it is a stored proc and/or batch updates, it may be more performant to declare a variable for the current datetime, and use that to update this value.
Simply create a trigger.
After update, set this value to getdate(). I currently can't find some articles about the syntax, but I'm sure you can do better ;)
This is base of SilverSkin answer. I just update his statement to include the necessary JOIN.
CREATE TRIGGER updateDate
ON dbo.Table
AFTER UPDATE
AS
UPDATE Table
SET ModifiedDate = GetDate() -- or sysdatetimeoffset()
JOIN Table t JOIN Inserted i ON t.Id = i.Id
This is a syntax for SQL Server 2005.
Related
After updating rows in a table I would like to mark all the updated rows with the date that they have been updated.
What code do i need to write to do this
p.s. I should have stated that i am updating using a view because it helps me see clearly what data needs updating.
You can use a trigger that fires after update to do this.
Given a table like:
create table your_table (id int primary key, val int, last_update datetime)
this trigger will set the last_update value whenever you update something in the table.
CREATE TRIGGER trigger_name ON your_table
AFTER UPDATE AS
BEGIN
UPDATE your_table
SET your_table.last_update = GETDATE()
FROM your_table t
JOIN inserted i ON t.id = i.id
END
For the complete syntax and options for the trigger, see the documentation.
If you have option to do in application or Database, Application is better way for doing this. (For example in BaseDAL class)
If the application is not an option you can do it in database Trigger and updating the rows.
My table has two columns: Amount and Date
When I am adding new values, I want to update the amount if there is already a record with that date. If there is not, I want to just insert my new values.
something like:
if exists(select * from table where date = #date)
update table set amount = #amount where date = #date
else
insert table (amount, date) select #amount, date
Assuming you have at least SQL Server 2008, you could use the MERGE keyword. This keyword was added specifically for cases like yours. You specify a MERGE clause (basically a join) and then statements telling it how to handle when it does or doesn't find a match.
There's a decent example at the bottom that shows merging between a target table and a source "table" created out of a single row of parameters. To boil it down a bit, you could use something like:
MERGE [TargetTable] AS target -- This is the table we'll be updating
USING (SELECT #Date) AS source (Date) -- These are the new values
ON (target.Date = source.Date) -- Here we define how we find a "match"
WHEN MATCHED THEN -- If the date already exists:
UPDATE SET Amount = #Amount
WHEN NOT MATCHED THEN -- If the date does not already exist:
INSERT (Date, Amount) VALUES (#Date, Amount)
Note that the nested UPDATE and INSERT clauses do not specify a table. That is because we already told SQL Server which table to perform those actions on when we defined our target table (the table specified right after the MERGE keyword).
Update: This functionality is apparently not supported by SQL Server CE, so it will not work in your specific case. I am leaving this answer here as it may help others attempting to do something similar in the full version of SQL Server. For the SQL Server CE solution, check out BJury's answer.
As an alternative to IF .. NOT EXISTS, you could assert an UPDATE, and fall back on an insert. This is usually quite a performant UPSERT pattern if data generally does exist already.
UPDATE MyTable
SET Amount = #NewAmount
WHERE Date = #Date;
IF ##ROWCOUNT = 0
INSERT INTO MyTable(Amount, Date) VALUES (#NewAmount, #Date);
If you are using nhibernate ORM, then you can use SaveOrUpdate session method.
I know when you insert a value into db, it set that column value as current datetime,
does it apply to it when you run a update statement?
e.g.
table schema:
Id, Name, CreatedDate(getdate())
when i insert into table id = 1 , name = 'john' it will set createdDate = current date
if i run an update statement
update table set name="john2" where id =1
Will it update the createdDate?
No, a DEFAULT CONSTRAINT is only invoked on INSERT, and only when (a) combined with a NOT NULL constraint or (b) using DEFAULT VALUES. For an UPDATE, SQL Server is not going to look at your DEFAULT CONSTRAINT at all. Currently you need a trigger ( see How do I add a "last updated" column in a SQL Server 2008 R2 table? ), but there have been multiple requests for this functionality to be built in.
I've blogged about a way to trick SQL Server into doing this using temporal tables:
Maintaining LastModified Without Triggers
But this is full of caveats and limitations and was really only making light of multiple other similar posts:
A System-Maintained LastModifiedDate Column
Tracking Row Changes With Temporal
Columns
How to add “created” and “updated” timestamps without triggers
Need a datetime column that automatically updates
wow - hard to understand...
i think NO based on the clues.
if you insert a record with a NULL in a column, and that column has a default value defined, then the default value will be stored instead of null.
update will only update the columns specified in the statement.
UNLESS you have a trigger that does the special logic - in which case, you need to look at the trigger code to know the answer.
if your update statement tell to update a column with getfate() it will, but if you just update a name for example and you have a createdate column (which was inserted with getdate()), this columns wont be affected.
You can achieve this using DEFAULT constraint like i did it with OrderDate field in below statement.
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
OrderDate date DEFAULT GETDATE()
)
Is it possible in SQL Server 2005 to set a default value for a column which comes from another table through a query or something?
Yes.
You can use a scalar UDF in a default constraint.
This will be RBAR ("Row By Agonizing Row") for multi row inserts however and a trigger might well be more efficient.
I agree with both of Martin's points. Therefore, I use a trigger to avoid the potential performance penalty of RBAR in case someone does a mass import of data into the table. In the following code, we want MyTable.MyColumn set to be DefaultSource.DefaultMyColumn if no value was supplied for MyColumn and we have a populated default value. This assumes that there is a MyTable.DefaultId (preferably with a Foreign Key) so we can get the default value from the correct row in DefaultSource.
CREATE TRIGGER [dbo].[TR_MyTable_AI_Default]
ON [dbo].[MyTable]
AFTER INSERT
AS
SET NOCOUNT ON;
UPDATE m
SET [MyColumn] = ds.[DefaultMyColumn]
FROM inserted i
JOIN [dbo].[MyTable] m ON i.[PrimaryKey] = m.[PrimaryKey]
JOIN [dbo].[DefaultSource] ds ON i.[DefaultId] = ds.[DefaultId]
WHERE a.[MyColumn] IS NULL
AND df.[DefaultMyColumn] IS NOT NULL;
Do not try to update the inserted special table directly, but instead update the base table for the trigger.
I was given a task to display when a record in the database was added, however the previous developers never made a field for this, and I can't go back and make up dates for all the existing records. Is there an easy way to extract out a record Creation date from a SQL server 2000 query.
SELECT RECORD_CREATED_DATE FROM tblSomething WHERE idField = 1
The RECORD_CREATED_DATE isn't a field in the existing table. Is there some sort of SQL Function to get this information ?
If it's not stored as a field, the info is lost after the transaction log recycles (typically daily), and maybe even sooner.
No, unfortunately date of insert or last update are not automatically stored with each record.
To do that, you need to create two datetime columns in your table (e.g. CreatedOn, UpdatedOn) and then in an INSERT trigger set the CreatedOn = getdate() and in the UPDATE trigger set the UpdatedOn = getdate().
CREATE TRIGGER tgr_tblMain_Insert
ON dbo.tblMain
AFTER INSERT
AS
BEGIN
set nocount on
update dbo.tblMain
set CreatedOn = getdate(),
CreatedBy = session_user
where tblMain.ID = INSERTED.ID
END
I also like to create CreatedBy and UpdatedBy varchar(20) columns which I set to session_user or update through other methods.
I would start with putting this information in from now on. Create two columns, InsertedDate, LastUpdatedDate. Use a default value of getdate() on the first and an update trigger to populate the second (might want to consider UpdatedBy as well). Then I would write a query to display the information using the CASE Statement to display the date if there is one and to display "Unknown" is the field is null. This gets more complicated if you need to store a record of all the updates. Then you need to use audit tables.
I'm not aware of a way you can get this information for existing records. However, going forward you can create an audit table that stores the TableName and RecordCreateDate (or something similar.
Then, for the relevant tables you can make an insert trigger:
CREATE TRIGGER trigger_RecordInsertDate
ON YourTableName
AFTER INSERT
AS
BEGIN
-- T-SQL code for inserting a record and timestamp
-- to the audit table goes here
END
create another column and give it a default of getdate() that will take care of inserted date, for updated date you will need to write an update trigger