gpt4 book ai didi

sql - 想要在日期时间列中默认插入当前时间,并在 sql server 中插入日期

转载 作者:行者123 更新时间:2023-12-04 14:22:51 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Add default value of datetime field in SQL Server to a timestamp

(12 个回答)


5年前关闭。




我想在日期时间列中使用插入的日期自动插入当前时间。默认情况下,它插入 00:00:00

我创建了触发器

Create trigger tr_tm on emp
after insert,update
as
declare @tme time

set @tme=(select CONVERT(varchar(7),start_date,108) from emp)

update emp
set @tme=convert(varchar(8),getdate(),108)
where @tme='00:00:00'
go

但它显示错误:

Msg 512, Level 16, State 1, Procedure tr_te, Line 15 Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. The statement has been terminated.



怎么可能??

提前致谢..

最佳答案

一种方法是添加 default constraint到您的专栏。当您不提供值时,将使用默认约束来填充列。

示例

-- Example table.
CREATE TABLE Example
(
A INT,
B TIME DEFAULT(CAST(GETDATE() AS TIME))
)
;

插入数据时,如果我们不提供值,将应用默认值。
-- Adding data, without referencing column.
INSERT INTO Example
(
A
)
VALUES
(1),
(2),
(3)
;

您还可以明确指定要应用默认值。
-- Adding data, using DEFAULT.
INSERT INTO Example
(
A,
B
)
VALUES
(10, DEFAULT),
(20, DEFAULT),
(30, DEFAULT)
;

您还可以选择忽略默认值并提供您自己的值。
-- Adding data without using default value.
INSERT INTO Example
(
A,
B
)
VALUES
(100, '09:30:00'),
(200, '10:30:00'),
(300, '11:30:00')
;

上面的三个查询返回:
A   B
1 13:19:28.1900000
2 13:19:28.1900000
3 13:19:28.1900000
10 13:19:28.1900000
20 13:19:28.1900000
30 13:19:28.1900000
100 09:30:00.0000000
200 10:30:00.0000000
300 11:30:00.0000000

关于sql - 想要在日期时间列中默认插入当前时间,并在 sql server 中插入日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36935602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com