Reputation: 32778
I have this SQL Server table:
CREATE TABLE [dbo].[Synonym]
(
[SynonymId] [int] NOT NULL,
[WordFormId] [int] NOT NULL,
[Ascii] AS (ascii([Text])) PERSISTED,
[Text] [varchar](max) NOT NULL,
[Version] [timestamp] NULL,
[CreatedBy] [int] NULL,
[CreatedDate] [datetime] NULL,
[ModifiedBy] [int] NULL,
[ModifiedDate] [datetime] NULL,
PRIMARY KEY CLUSTERED ([SynonymId] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
How can I set the CreatedDate to the current date for all of the rows?
Upvotes: 0
Views: 1828
Reputation: 912
Select Table Column Name where you want to get default value of current date:
ALTER TABLE [dbo].[Table_Name]
ADD CONSTRAINT [Constraint_Name]
DEFAULT (getdate()) FOR [Column_Name]
Alter table query:
Alter TABLE [dbo].[Table_Name]
(
[PDate] [datetime] Default GetDate()
)
you can also do this from SSMS GUI.
Upvotes: 1
Reputation: 32980
If want to save the date when the record was created, add a default constraint to the table:
ALTER TABLE [Synonym] ADD CONSTRAINT createdDate DEFAULT GETDATE() FOR [CreatedDate]
Then if you insert a record you don't need to specify the createdDate and get the current date value.
If you want to set the date for all existing records simply run an update
UPDATE [Synonym] SET [CreatedDate] = GETDATE()
or for all records whose CreatedDate
is null:
UPDATE [Synonym] SET [CreatedDate] = GETDATE() WHERE [CreatedDate] IS NULL
Upvotes: 2