How to add a column month? The month must be extracted from a date column in the same table. I know that this extracts the month but how to add it please
SELECT
MONTH(columndate) AS month
FROM
TableTIME;
DROP TABLE IF EXISTS dbo.Temp;
CREATE TABLE dbo.Temp
(
Temp_ID TINYINT IDENTITY(1,1) NOT NULL PRIMARY KEY,
TempDate DATE NOT NULL DEFAULT GETDATE()
)
GO
INSERT dbo.Temp(TempDate)
VALUES(GETDATE()),('20120430');
GO
ALTER TABLE dbo.Temp
ADD TempMonth AS DATEPART(MM,Tempdate) PERSISTED
GO
SELECT * FROM dbo.Temp;
you only need add a int column, you also can add check rule on this column, For example:
ALTER TABLE dbo.MyTable ADD mn INT CHECK(mn BETWEEN 1 AND 12)
If you really need to have the month column, just add an integer column to the table and do and update with the extracted month:
update TableTIME set monthcolumn = MONTH(columndate)
It's not clear what is the purpose of that but, if this month will never change, I suggest you to select the MONTH(columndate) only when you need it or the full date and extract the month in the business logic.
Related
Currently I have a column named CreatedDate in a Shipper table I created. It is nullable. My task is to change the created date to be a required field, not allow nulls, and have a default of GetDate(). This has to be done in a single query... Keep in mind there is no data in my table yet. I've tried the following code and I can't seem to get it to work. This is a homework assignment and I'm only looking for guidance. Any help would be greatly appreciated. Thanks in advance.
USE Business
ALTER TABLE Shipper
ALTER COLUMN CreatedDate date NOT NULL
CONSTRAINT CNDefaultCreatedDate
DEFAULT GETDATE() For CreatedDate;
Two different statements, I assume this is SQL Server:
--Add the default
ALTER TABLE [Shipper] --What table
ADD CONSTRAINT [def_createddate] --Give the constraint a name
DEFAULT GETDATE() FOR [CreatedDate]; --default of what for which column
--Set to not allow NULL
ALTER TABLE [Shipper] --What table
ALTER COLUMN [CreatedDate] DATE NOT NULL; --altering what column and either NULL or NOT NULL
Understand adding a default will not update existing data. I know you mentioned your table does not have data, but in the future the null values must be updated to some value before the ALTER COLUMN NOT NULL is allowed.
Here's reference to the MS documentation ALTER TABLE
If the column did not already exist you can add it, set it not null and then even update existing rows in one statement:
--If Shipper did not already have the column CreatedDate
ALTER TABLE [Shipper]
ADD [CreatedDate] DATE NOT NULL
CONSTRAINT [def_createddate] DEFAULT GETDATE()
WITH VALUE --if column is nullable use this and it will update existing records with the default. It column is NOT NULL this is applied by default.
Have you tried this:
USE Business
ALTER TABLE Shipper
ALTER COLUMN CreatedDate date NOT NULL DEFAULT GETDATE();
I want to update the column transe_date from int into date ..
update fci
set fci.transe_date= convert(date,convert(varchar(8),transe_date));
Rather than creating a new column, completing an UPDATE statement, renaming your old column, and then the new, you could use 2 ALTER statements. You can't implicity convert an int to date, but you can implicitly convert an int to varchar and then from a varchar to a date:
USE Sandbox;
GO
CREATE TABLE dbo.SomeTable (DateColumn int);
INSERT INTO dbo.SomeTable (DateColumn)
VALUES (20160101),
(20160307),
(20180920);
GO
SELECT *
FROM dbo.SomeTable
GO
ALTER TABLE dbo.SomeTable ALTER COLUMN DateColumn varchar(8);
ALTER TABLE dbo.SomeTable ALTER COLUMN DateColumn date;
GO
SELECT *
FROM dbo.SomeTable
GO
DROP TABLE dbo.SomeTable
Of course, this assumes that all your ints are valid date values.
Edit: If you do have values that aren't valid date values, you'll need to identify and correct these first. You could identify these by using TRY_CONVERT:
SELECT YourIntColumn
FROM dbo.YourTable
WHERE TRY_CONVERT(date,CONVERT(varchar(11),YourIntColumn)) IS NULL;
There's no need to put a TRY_CONVERT on the varchar(11), as an int can always be converted to a varchar. I used varchar(11) as well (instead of varchar(8)( because the largest value, in character length, you could have would be -2147483648 (which is 11 characters long).
Make a dummy column to hold data
Change data type of existing column
put all values back after converting using the column made
Drop the dummy column
Cleaning the new column
Script sample will be
/*1*/
Alter Table FCI
Add tempcol DateTime
Go
/*2*/
update fci
set tempcol = convert(date,convert(varchar(8),transe_date));
/*3*/
Alter Table FCI
alter column transe_date DateTime
Go
/*4*/
update fci
set transe_date = tempcol;
/*5*/
Alter Table FCI
drop column tempcol
Go
If the whole data is Date then directly converting the column type can do the job, the above process is the safe side process for start.
If you want to convert the int values into dates, you will first have to add a new column (transe_date2) of that type. Then, you can store the converted values in this new column:
update fci
set fci.transe_date2 = convert(date,convert(varchar(8),transe_date));
Having done this, I suggest to use SSMS to drop the old column and rename the new one.
Here are the steps:
--add date column
ALTER TABLE fci ADD transe_date2 date;
GO
--do conversions
UPDATE fci SET transe_date2=CONVERT(date,CONVERT(varchar(8),transe_date),112);
GO
--drop int column
ALTER TABLE fci DROP COLUMN transe_date;
GO
--rename temporary column to transe_date
EXEC sp_rename 'fci.transe_date2', 'transe_date', 'COLUMN';
My table has a DATE type column but I need to see the GMT information my idea is change to timestamp column. How to change the column which already has value filled?
create table PRO_TFESTIVO ( oid_festivo NUMBER(10) not null, fecha_hora_envio DATE to TIMESTAMP );
Thank you all!!
You cannot change the DATE/TIMESTAMP type without:
Create a temporary column with the existing values;
Create a new table with the original name;
Fill the existing values to the "new" column.
Convert DATE to TIMESTAMP WITH TIME ZONE:
ALTER TABLE pro_tfestivo RENAME COLUMN FECHA_HORA_ENVIO TO OLD_FECHA_HORA_ENVIO;
ALTER TABLE pro_tfestivo ADD FECHA_HORA_ENVIO TIMESTAMP WITH TIME ZONE;
UPDATE pro_tfestivo SET FECHA_HORA_ENVIO = FROM_TZ(CAST(OLD_FECHA_HORA_ENVIO AS TIMESTAMP), 'GMT');
ALTER TABLE pro_tfestivo DROP COLUMN OLD_FECHA_HORA_ENVIO;
Plus :) Convert TIMESTAMP WITH TIME ZONE to DATE:
ALTER TABLE pro_tfestivo RENAME COLUMN FECHA_HORA_ENVIO TO OLD_FECHA_HORA_ENVIO;
ALTER TABLE pro_tfestivo ADD FECHA_HORA_ENVIO DATE;
UPDATE pro_tfestivo SET FECHA_HORA_ENVIO = CAST(to_timestamp_tz(OLD_FECHA_HORA_ENVIO, 'dd/mm/yyyy hh24:mi:ssXFF TZR') at time zone 'GMT' AS DATE);
ALTER TABLE pro_tfestivo DROP COLUMN OLD_FECHA_HORA_ENVIO;
If you are luck enough to have the "Advanced Replication" license, another way to do this would be to use the DBMS_REDEFINITION package
--your existing table
create table MY_SCHEMA.MY_TABLE ( START_DATE DATE );
INSERT INTO MY_TABLE VALUES (SYSDATE);
commit;
--The new Structure of your table
create table MY_TABLE_NEW ( START_DATE TIMESTAMP );
begin
dbms_redefinition.start_redef_table(
uname=>'MY_SCHEMA',
orig_table =>'MY_TABLE',
int_table =>'MY_TABLE_NEW',
col_mapping =>'cast(START_DATE as timestamp) START_DATE',
options_flag =>dbms_redefinition.cons_use_rowid);
end;
/
exec dbms_redefinition.finish_redef_table('MY_SCHEMA','MY_TABLE','MY_TABLE_NEW');
After that, your original table ( which will keep it's name MY_TABLE ) should have it's column changed from DATE to TIMESTAMP with all the data converted on the fly. The advantage is that your original table stays available to the other applications during the process so you might do it in production without any interruption of service
PS : I don't have the license on my test DB so I can't test it now, but it should work
I am using SQL Server 2005.
I have a composite key comprising of these columns:
UserID ..... int
ADate ..... datetime
If I enter two similar dates with different time for a user, it is permitting that record. But I want it to restrict because of similar dates.
How to make it restrict when identical date parts are inserted?
Consider your table
create table tbl (
userid int,
adate datetime
)
You can add a COMPUTED column
alter table tbl add adateonly as datediff(d,0,adate);
So that you can create a UNIQUE constraint over it:
alter table tbl add constraint uq_tbl_date unique(userid, adateonly);
If I'm understanding your question you want to create a composite restriction with and index or other method?
1) With an index, can you add another column varchar(8) with just the date like: yyyymmdd, then with a trigger or before the inserts you can generate the date string.
2) create a trigger on the table and validate the the two keys, probably a insert and update trigger.
hope this helps,
José Cruz
I've got a table that collects forms submitted from our website, but for some reason, when they created the table, they didn't put a timestamp in the table. I want it to enter the exact date and time that the record was entered.
I know it's in there somewhere, but I can't seem to find how to set the default value (like in Access, you use getNow() or Now()) but I don't know where to put it.
For modifying an existing column in an existing table:
ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETDATE() FOR YourColumn
This can also be done through the SSMS GUI.
Put your table in design view (Right click on table in object explorer->Design)
Add a column to the table (or click on the column you want to update if it already exists)
In Column Properties, enter (getdate()) in Default Value or
Binding field as pictured below
In that table in SQL Server, specify the default value of that column to be CURRENT_TIMESTAMP.
The datatype of that column may be datetime or datetime2.
e.g.
Create Table Student
(
Name varchar(50),
DateOfAddmission datetime default CURRENT_TIMESTAMP
);
While the marked answer is correct with:
ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETDATE() FOR YourColumn
You should always be aware of timezones when adding default datetime values in to a column.
Say for example, this datetime value is designed to indicate when a member joined a website and you want it to be displayed back to the user, GETDATE() will give you the server time so could show discrepancies if the user is in a different locale to the server.
If you expect to deal with international users, it is better in some cases to use GETUTCDATE(), which:
Returns the current database system timestamp as a datetime value. The database time zone offset is not included. This value represents the current UTC time (Coordinated Universal Time). This value is derived from the operating system of the computer on which the instance of SQL Server is running.
ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETUTCDATE() FOR YourColumn
When retrieving the values, the front end application/website should transform this value from UTC time to the locale/culture of the user requesting it.
Disallow Nulls on the column and set a default on the column of getdate()
/*Deal with any existing NULLs*/
UPDATE YourTable SET created_date=GETDATE() /*Or some sentinel value
'19000101' maybe?*/
WHERE created_date IS NULL
/*Disallow NULLs*/
ALTER TABLE YourTable ALTER COLUMN created_date DATE NOT NULL
/*Add default constraint*/
ALTER TABLE YourTable ADD CONSTRAINT
DF_YourTable_created_date DEFAULT GETDATE() FOR created_date
The syntax for this when creating a new table is:
CREATE TABLE MyTable
(
MYTableID INT IDENTITY(1,1),
CreateDate DATETIME NOT NULL CONSTRAINT DF_MyTable_CreateDate_GETDATE DEFAULT GETDATE()
)
This works for me...
ALTER TABLE [accounts]
ADD [user_registered] DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ;
This also works:
CREATE TABLE Example(
...
created datetime default GETDATE()
);
Or:
ALTER TABLE EXAMPLE ADD created datetime default GETDATE();
This worked for me. I am using SQL Developer with Oracle DB:
ALTER TABLE YOUR_TABLE
ADD Date_Created TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL;
Let's say you create a database table for a registration system.
IF OBJECT_ID('dbo.registration_demo', 'U') IS NOT NULL
DROP TABLE dbo.registration_demo;
CREATE TABLE dbo.registration_demo (
id INT IDENTITY PRIMARY KEY,
name NVARCHAR(8)
);
Now a couple people register.
INSERT INTO dbo.registration_demo (name) VALUES
('John'),('Jane'),('Jeff');
Then you realize you need a timestamp for when they registered.
If this app is limited to a geographically localized region, then you can use the local server time with GETDATE(). Otherwise you should heed Tanner's consideration for the global audience with GETUTCDATE() for the default value.
Add the column with a default value in one statement like this answer.
ALTER TABLE dbo.registration_demo
ADD time_registered DATETIME DEFAULT GETUTCDATE();
Let's get another registrant and see what the data looks like.
INSERT INTO dbo.registration_demo (name) VALUES
('Julia');
SELECT * FROM dbo.registration_demo;
id name time_registered
1 John NULL
2 Jane NULL
3 Jeff NULL
4 Julia 2016-06-21 14:32:57.767
To make it simpler to follow, I will summarize the above answers:
Let`s say the table is called Customer
it has 4 columns/less or more...
you want to add a new column to the table where every time when there is insert... then that column keeps a record of the time the event happened.
Solution:
add a new column, let`s say timepurchase is the new column, to the table with data type datetime.
Then run the following alter:
ALTER TABLE Customer ADD CONSTRAINT DF_Customer DEFAULT GETDATE() FOR timePurchase
In SQLPlus while creating a table it is be like as
SQL> create table Test
( Test_ID number not null,
Test_Date date default sysdate not null );
SQL> insert into Test(id) values (1);
Test_ID Test_Date
1 08-MAR-19