使用 T-SQL 将当前日期插入日期列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7981684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert current date into a date column using T-SQL?
提问by nhat
I'm trying to insert a date when a user decides to deactivate or activate an UserID. I'm trying to use a SP to trigger that but apparantly this is harder than I thought it would be.
我试图在用户决定停用或激活用户 ID 时插入日期。我正在尝试使用 SP 来触发它,但显然这比我想象的要难。
I can do a
我可以做一个
SELECT GETDATE()
to get the date but is there a way to insert that information from GETDATE and put it into a column I want?
获取日期,但有没有办法从 GETDATE 插入该信息并将其放入我想要的列中?
回答by harriyott
Couple of ways. Firstly, if you're adding a row each time a [de]activation occurs, you can set the column default to GETDATE() and not set the value in the insert. Otherwise,
几种方式。首先,如果您在每次 [de]activation 发生时添加一行,您可以将列默认设置为 GETDATE() 而不是在插入中设置值。除此以外,
UPDATE TableName SET [ColumnName] = GETDATE() WHERE UserId = @userId
回答by El Ronnoco
To insert a new row into a given table (tblTable) :
要在给定表 (tblTable) 中插入新行:
INSERT INTO tblTable (DateColumn) VALUES (GETDATE())
To update an existing row :
要更新现有行:
UPDATE tblTable SET DateColumn = GETDATE()
WHERE ID = RequiredUpdateID
Note that when INSERT
ing a new row you will need to observe any constraints which are on the table - most likely the NOT NULL
constraint - so you may need to provide values for other columns eg...
请注意,在INSERT
创建新行时,您需要观察表上的任何约束 - 很可能是NOT NULL
约束 - 因此您可能需要为其他列提供值,例如...
INSERT INTO tblTable (Name, Type, DateColumn) VALUES ('John', 7, GETDATE())
回答by Curt
UPDATE Table
SET DateColumn=GETDATE()
WHERE UserID=@UserID
If you're inserting into a table, and will always need to put the current date, I would recommend setting GETDATE()
as the default value for that column, and don't allow NULLs
如果您要插入到表中,并且始终需要输入当前日期,我建议将GETDATE()
其设置为该列的默认值,并且不允许 NULL
回答by James Johnson
If you're looking to store the information in a table, you need to use an INSERT or an UPDATE statement. It sounds like you need an UPDATE statement:
如果您希望将信息存储在表中,则需要使用 INSERT 或 UPDATE 语句。听起来您需要一个 UPDATE 语句:
UPDATE SomeTable
SET SomeDateField = GETDATE()
WHERE SomeID = @SomeID
回答by Mike Walsh
You could use getdate() in a default as this SO question's accepted answer shows. This way you don't provide the date, you just insert the rest and that date is the default value for the column.
您可以在默认情况下使用 getdate(),因为此SO 问题已接受的答案显示。这样你就不用提供日期,你只需插入其余的日期,该日期是该列的默认值。
You could also provide it in the values list of your insert and do it manually if you wish.
您也可以在插入的值列表中提供它,并根据需要手动执行。