store date only, not the the time in datetime field - sql

This is a trivial question, I added a field
Alter table MyTbl add datecreated smalldatetime default CONVERT(varchar(10),GetDate(),101)
When I go check the new field, it shows not only the date but also time. I check the table definition (right click on table -> Modify in SSMS) and it does say the default value as GETDATE() [it discarded the convert(...) by default]. Why is this so. Is there a way to give a default date only to datetime field and not the time.
I ended up leaving the time field as it is because it is better to see what is going on in the table esp in initial test phase.

I just tried your ALTER statement, and it works as you expect; when I enter a row without including datecreated, it sets the value to the date with a time of 00:00:00.
The fact that you checked the table definition and it says the default is GETDATE() leads me to believe the column already existed and your ALTER failed.

this will reset the time section to zero
DateAdd(day, DateDiff(day, 0, PayDate), 0)

Just because you are converting the datetime returned from getdate() to a varchar(10), there is another implicit cast from varchar(10) to datetime, as it is the datatype for your field.
You need to have the datecreated field datatype a varchar(10).
Your alter table statement should be:
Alter table MyTbl add datecreated varchar(10) default CONVERT(varchar(10),GetDate(),101)

Related

Cast/Convert nvarchar to datetime(2)

Since I described it poorly last time, again
i have table:
id time_stamp
1 12.01.20 15:34:34,000000000 EUROPE/PRAGUE
2 10.01.20 10:15:15,000000000 EUROPE/PRAGUE
3 09.01.20 05:55:42,000000000 EUROPE/PRAGUE
Table have huge amount these data. Column timestamp is data type "nvarchar". And i need to sort datas by date or use in clauses WHERE for constraint by date, so i need to convert "timestamp" to datetime. But I can't. I tried convert and cast but still failed.
From #Larnu i got advice, but didnt work, because I'm stupid and inaccurately described the problem.
UPDATE dbo.YourTable
SET [timestamp] = CONVERT(nvarchar(20),TRY_CONVERT(datetime2(0), [timestamp], 104), 126);
Now you can ALTER the table and change the data type to a datetime2(0):
ALTER TABLE dbo.YourTable ALTER COLUMN [timestamp] datetime2(0) NULL;
any advice on how to change with respect to the time_stamp column.
Thx.

Add column to existing table set default to sysdate for existing records and tomorrows date for new entries

Hi I am learning SQL while I found below task,
Insert a new column StartDate in existing table and for the existing records should have sysdate and for new entries should have tomorrow's date.
until now I did
ALTER TABLE test
ADD StartDate DATETIME NOT NULL DEFAULT (GETDATE());
from here I unable to go forward i am thinking the task itself is not correct am i thinking correct or can we perform this task pls anyone help me out.
First read Sean’s comment on making the column NULLABLE. Then, you'd change your command to:
The default should be dateadd(day,1,getdate()). This would work for future inserts where you don't specify a value on insert.
ALTER TABLE test
ADD StartDate DATETIME NULL DEFAULT (DATEADD(DAY,1,GETDATE()));
For the other rows, you simply need to update then once you have made this table change.
update table test
set StartDate = getdate()
where StartDate is null --which is every row that wasn't inserted after the change
Then, alter the column to make it NOT NULL
ALTER TABLE test
ALTER COLUMN StartDate DATETIME NOT NULL DEFAULT (DATEADD(DAY,1,GETDATE()));
Try this:
ADD StartDate2 DATETIME NOT NULL DEFAULT (DATEADD(DAY, 1,GETDATE()));

Filling in a datetime field as empty

I need to add a new record to a database and one of the columns in my table is 'paymentDate', which is a "DateTime" field. Now the record I need to add is one in which the paymentDate is not known. I can't put in 'NULL' as SQL says 'Column 'paymentDate' cannot be null'. Also the '""' doesn't work in a datetime field.
If you have a paymentDate column and you don't know the date, then the column should allow NULL values. So, you should fix the data model:
alter table t alter column paymentDate datetime;
This will remove the not-NULL constraint, so you can add the data that you have.
I would be a little cautious, though. Why are you trying to add a row with an unknown payment date, if the designer of the table thought the value should never be NULL?

How do I set a value for existing rows when creating a new timestamp column?

I have the following table:
Study id
Pepsi 1
Coke 2
Sprite 3
I need to add a new column timestamp in the above table. i.e, study creation time and date will be stored in this column. What value should I have set for existing rows? Or should the "Timestamp" column have a value only for newly created rows?
I have used the following query to add the new column:
alter table Study add Timestamp datetime
There is no way to tell you what value you should set for existing rows - that is up to you to decide. If you can somehow retrieve the creation time by piecing together other information, then perhaps you can do this one by one, or you could just leave the existing rows to NULL.
Setting a default like GETDATE() for the column, and setting it to NOT NULL, forces all of the existing rows to inherit the current date and time - and you won't be able to set those back to NULL. I'm quite opposed to using garbage token values like 1900-01-01 to represent unknown, and I also don't believe in modifying the code to say something like "if the date is October 8, 2013 then that's because we just didn't know." So I would suggest adding a NULLable column with a default:
ALTER TABLE dbo.Study ADD CreationTime DATETIME NULL DEFAULT CURRENT_TIMESTAMP;
GO
Note that if you leave the column nullable, then the DEFAULT constraint is only useful if DML never sets it to NULL. If an INSERT statement, for example, explicitly places NULL there, the default is ignored. A way around this is to use a trigger (just like you would handle an update):
CREATE TRIGGER dbo.StudyCreationTime
ON dbo.Study
FOR INSERT
AS
BEGIN
SET NOCOUNT ON;
UPDATE s
SET s.CreationTime = CURRENT_TIMESTAMP
FROM dbo.Study AS s
INNER JOIN inserted AS i
ON s.StudyID = i.StudyID;
END
GO
what value should i have to set for previous studies
This would have to be defined by your business. This doesn't require a technical answer, so no one here can tell you what is right.
I have used below query to adding new column:
alter table Study add Timestamp datetime
This will work just fine, though this will allow nulls. I might suggest making this column non-null, adding a default, and changing the name of the column slightly since timestamp is a reserved word in SQL Server (a datatype that has not much to do with dates or times):
alter table Study add CreateDate datetime not null default current_timestamp;
Note that this will set all rows to the current date and time, so you may want to update them if you have more accurate data. Alternatively, simply create the column as nullable and existing rows won't get the default value, but rather null instead.
Another choice you might have to make is whether to use local time or UTC time (e.g. default getutcdate()). You might want to use the same time that your servers use or that other "CreateDate" columns use.

mysql automatically store record creation timestamp

Is there some way mysql can store timestamp automatically in a record row whenever that it is created. I was trying to use timestamp(data type) with current_timestamp as default value but then realised this will get updated everytime the record is updated. I just need something that will store create timestamp.
Thanks
Set the DEFAULT constraint to use CURRENT_TIMESTAMP:
CREATE TABLE ...
your_date_column DATETIME DEFAULT CURRENT_TIMESTAMP
...
For an existing table, use the ALTER TABLE statement:
ALTER TABLE your_table
ALTER COLUMN date_column SET DEFAULT CURRENT_TIMESTAMP
Unless you specify a value to for the date_column, the default will be the date & time the INSERT statement was run. NULL and DEFAULT or valid values to use the default constraint otherwise, assuming the column is nullable.
You can get the full details on timestamps in MySQL at https://dev.mysql.com/doc/refman/5.0/en/timestamp-initialization.html.
The point that you care about is that if you define a timestamp column as DEFAULT CURRENT_TIMESTAMP clause and don't have an ON UPDATE clause, the column has the current timestamp for its default value but is not automatically updated.
But be warned. The obvious thing to want to do is to have two timestamp columns, one being the creation time and the other being the last update time. Unfortunately it is a documented MySQL limitation that MySQL does not support this. I have no idea why MySQL has such an odd limitation - no other major database has problems with this common use case.
FYI = "Datetime" is date and time fixed. "Timestamp" is variable date and time-- system time.
So, Have two columns. One Create Col, One Update Col.
The following command will create a hello table
1. id integer
2. create_at with current time.
create table hello (id int, created_at datetime DEFAULT CURRENT_TIMESTAMP);
Create Table myTableName
(
userId int primary key
userJoiningDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
https://www.mysqltutorial.org/mysql-timestamp.aspx
Here is how you can create a column in which the time stamp is recorded when it is created. If you want to know How to update timeStamp each time that row is changed/updated, Check the above link.
SELECT * FROM test WHERE timestamp >= CURDATE() AND timestamp < CURDATE() + INTERVAL 1 DAY ORDER BY timestamp;