如何将表格中每一行的日期设置为当前日期?

时间:2016-06-12 05:12:34

标签: sql-server

我有这个SQL Server表:

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]

如何将CreatedDate设置为所有行的当前日期?

2 个答案:

答案 0 :(得分:2)

如果要在创建记录时保存日期,请向表中添加默认约束:

ALTER TABLE [Synonym] ADD CONSTRAINT createdDate DEFAULT GETDATE() FOR  [CreatedDate]

然后,如果您插入记录,则不需要指定createdDate并获取当前日期值。

如果要设置所有现有记录的日期,只需运行更新

UPDATE [Synonym] SET [CreatedDate] = GETDATE()

CreatedDate为空的所有记录:

UPDATE [Synonym] SET [CreatedDate] = GETDATE() WHERE [CreatedDate] IS NULL 

答案 1 :(得分:1)

选择要获取当前日期默认值的表列名称:

ALTER TABLE [dbo].[Table_Name]
ADD  CONSTRAINT [Constraint_Name] 
DEFAULT (getdate()) FOR [Column_Name]

更改表格查询:

Alter TABLE [dbo].[Table_Name]
(
    [PDate] [datetime] Default GetDate()
)

您也可以从SSMS GUI执行此操作。

  1. 将您的表放在设计视图中(右键单击对象中的表 explorer-> Design)
  2. 在表格中添加一列(单击您所在的列     想要更新,如果它已经存在)
  3. 在“列属性”中,输入         (getdate())在默认值或Binding字段中,如下图所示
  4. SSMS GUI