rails: date type and GetDate - sql

This is a follow up to this question: Unique responses rails gem
I'm going to create an index based on the user id, url and a date type.
I want date type (not datetime type) because I want the day, the 24 hour day to be part of the index to avoid duplication of page views counts on the same day.
In other words: A view only counts once in a day by a visitor.
I also want the default value of that column (viewdate) to be the function GETDATE().
This is what I have in my migration:
execute "ALTER TABLEpage_viewsADD COLUMN viewdate datetime DEFAULTGETDATE()`"
But the value viewdate is always empty. What am I missing?
(as an aside, any other suggestions for accomplishing this goal?)

You're declaring the column as datetime type, not as date. Also I'm not sure MySQL supports default value seeding when altering the table.
Try this:
execute "ALTER TABLE page_views ADD COLUMN viewdate DATE"
PageView.update_all('viewdate=CURDATE()')

Related

Converting all data in a Varchar column to a date format

I'm working on a table with a column, 'Expiry Date', as a varchar with all data formatted as DD/MM/YYYY.
The creator of the table has used the wrong type for this expiry date column and now the client needs to filter and show all records before and after the current date as the time. This means the type needs to be changed to date or datetime type to be able to use the CURDATE() function.
However, the current format of the values does not satisfy and wont allow the type to change unless the format is changed to YYYY-MM-DD (or similar).
Is there any way to mass format the values in this column and this column alone as there are thousands of entries and formatting one by one would be extremely time consuming.
Let me assume that you are using MySQL.
Perhaps the simplest method is to add a generated column that is a date:
alter table t add column expiry_date_date as
(str_to_date(expiry_date, '%d/%m/%Y'));
You can also fix the data:
update t
set expiry_date = str_to_date(expiry_date, '%d/%m/%Y');
This will implicitly convert the result of str_to_date() to a date, which will be in the YYYY-MM-DD format.
More importantly, you can then do:
alter table t modify column expiry_date date;
Here is a db<>fiddle.
You can do similar operations in other databases, but the exact code is a bit different.
What you need is an update on that column, but before doing it I suggest you to check if the result is what you want.
select replace(expiry_date, '/', '-') new_expiry_date
from table_name
If this returns the results you want you can run the following update:
update table_name
set expiry_date = replace(expiry_date, '/', '-')
Of course you will need to replace expiry_date and table_name with the names of your column and table.

SQL - Conversion failed when converting date and/or time from character string

I have 3 tables in the database that I'm working on. Out of 3, two of the tables have columns that include dates. When I checked the information schema of the columns I found that dates have the wrong data type. If you see the picture below, the highlighted columns should be stored as DATE data type.
So, I used the following query to change their data type from varchar to DATE:
ALTER TABLE [dbo].[Customer]
ALTER COLUMN DOB DATE;
ALTER TABLE [dbo].[Transactions]
ALTER COLUMN tran_date DATE;
The error that I get is:
Conversion failed when converting date and/or time from character string.
Please let me know how I can fix this error. Thanks!
What you can do is update the value using try_convert() first and then alter the column name. Note: This will set any invalid values to NULL.
update customer
set dob = try_convert(date, dob);
alter table customer alter column dbo date;
If you want to see the bad values, then before you change the table, run:
select c.*
from customer c
where try_convert(date, dob) is null and dob is not null;
You may have other ideas on how to fix the values.
You can't change from varchar to date or time or datetime by altering the column. Why? Because SQL Server does not know if the field contains '1/1/2020' or 'My dog is cute'. You will have to rebuild the table with the proper data types and then CAST() or CONVERT() the values to a true date time.
Underneath the hood, this makes more sense. A char/varchar uses one byte per character. nchar/nvarchar uses 2 bytes per character. A datetime is a number, not a character. This means you need a routine that changes this into the correct number. If you want to get deeper, the number is the number of ticks (nanoseconds) since midnight on January 1, 0001 in the Gregorian Calendar. More info.

SQL Server default date time stamp?

I have a field that when something is inserted I want it to get the current Date & Time and insert this into the database. Is there a way to get the date & time, and set it as the default value?
Currently the default value is: (getdate()) Which sets only the date. How do I also set the time?
GETDATE() is a date and time in SQL Server.
Run SELECT GETDATE() to verify this.
What is the datatype of your field? If it's DATE then it will not hold time values as well.
One easy way is to give the field a default constraint:
create table YourTable
(
... other columns ...
CreateDt datetime default getdate(),
... other columns ...
)
A disadvantage of this method is that you can overwrite the value by specifying it in an insert clause.
Personally I would like to use GETUTCDATE() instead GETDATE() to avoid confusions.
SYSDATETIME() will get the current date and time.
Make sure the data type of the column is datetime, and not just date or it won't be able to hold a datetime.
Most SQL implementations (engines) do have CURRENT_TIMESTAMP function.

How to show timestamp's value as datetime

please tell me how to show the value of timestamp field of a table in datetime format (human understandable). and also how to use it in comparison while querying it.
Thanks
This can't be done. The TIMESTAMP datatype is misnamed - the name has been deprecated in favour of ROWVERSION in SQL 2008, which is a much clearer name.
TIMESTAMP stores an incrementing value which changes every time a row is updated.
If you want last updated dates stored against each row, you will need to add a DATETIME or SMALLDATETIME to your table and update it with the current date on each update.
You mean timestamp data type I think - http://msdn.microsoft.com/en-us/library/ms182776%28v=SQL.90%29.aspx
You can't convert it to datetime. According to the documentation in the link above :
> The timestamp data type is just an incrementing number and does not preserve a date or a time. To record a date or time, use a datetime data type.

What is difference between datetime and timestamp

What is difference between datetime and timestamp datatype in Sql Server?.
One is a date and time, the other is a column type that is updated every time a row is updated.
[Note timestamp is being deprecated; use rowversion instead]
Timestamp (deprecated synonym for rowversion) :
Is a data type that exposes automatically generated, unique binary numbers within a database. rowversion is generally used as a mechanism for version-stamping table rows. The storage size is 8 bytes. The rowversion data type is just an incrementing number and does not preserve a date or a time. To record a date or time, use a datetime2 data type.
http://msdn.microsoft.com/en-us/library/ms182776.aspx
Normally time-stamp used when ever you inserted new record into database automatically system would take default date time
ex : transaction like bank deposit or with draw
data-time datatype used at the movement of inserting the user defined date into the record
ex : date of birth
timestamp is the synonym for the rowversion data type and is subject to the behavior of data type synonyms. In DDL statements, use rowversion instead of timestamp wherever possible. In simple way to tell, It means the updating time of row. datetime means the time of creation of row.
DateTime is constant and other is changeable as the real time and local time.