简体   繁体   English

将默认列值从日期时间转换为varchar

[英]Convert default column value from datetime to varchar

I have to add a varchar column to a table which defaults to the current timestamp. 我必须在表中添加一个varchar列,该列默认为当前时间戳。 To do this I somehow need to convert the value from datetime to varchar. 为此,我需要以某种方式将值从datetime转换为varchar。

I tried the following 我尝试了以下

ALTER TABLE `TableName`
    CHANGE COLUMN `DocumentID` `DocumentID` VARCHAR(150) NULL DEFAULT CONVERT(NOW(), CHAR);

or 要么

ALTER TABLE `TableName`
    CHANGE COLUMN `DocumentID` `DocumentID` VARCHAR(150) NULL DEFAULT CONVERT(CURRENT_TIMESTAMP, CHAR);

I always get an error message, that my syntax is wrong. 我总是收到一条错误消息,提示我的语法错误。 I am using MariaDB and HeidiSQL. 我正在使用MariaDB和HeidiSQL。 Is there a way to do this? 有没有办法做到这一点?

EDIT: I am basically looking for a MySQL equivalent of the following SQL Server statement: 编辑:我基本上是在寻找与以下SQL Server语句等效的MySQL:

ALTER TABLE [dbo].[TableName] ADD  CONSTRAINT [DF_TableName_DocumentID]  DEFAULT (getdate()) FOR [DocumentID]

MariaDB document says MariaDB文件

In MariaDB 10.2.1 you can use most functions in DEFAULT. 在MariaDB 10.2.1中,您可以在DEFAULT中使用大多数功能。 Expressions should have parentheses around them. 表达式周围应带有括号。

Hence you may check for the version of MariaDB and use the right syntax (parenthesis around expression): 因此,您可以检查MariaDB的版本并使用正确的语法(围绕表达式的括号):

 (CONVERT(CURRENT_TIMESTAMP, CHAR))

Update 更新资料

As an alternative, you may use Trigger to set the function value for the stable releases (< 10.2) 或者,您可以使用“ 触发器”来设置稳定版本的功能值(<10.2)

If you use CURRENT_TIMESTAMP as default value, you must use the datatype that the function retrieves, in this case is a timestamp as you can see in the docs . 如果将CURRENT_TIMESTAMP用作默认值,则必须使用函数检索的数据类型,在这种情况下,这是时间戳, 如docs中所示

I don't know the reasons that may lead you to save this as a varchar. 我不知道可能导致您将其另存为varchar的原因。 I'm not sure but I think that MariaDB doesn't allow to call functions as default values so you can't convert CURRENT_TIMESTAMP as varchar. 我不确定,但我认为MariaDB不允许将函数作为默认值调用,因此您不能将CURRENT_TIMESTAMP转换为varchar。 You have an alternative approach, make an after insert trigger updating the field (you can call CONVERT(CURRENT_TIMESTAMP, VARCHAR) inside a trigger). 您有另一种方法,在插入后触发器中更新字段(可以在触发器内调用CONVERT(CURRENT_TIMESTAMP,VARCHAR))。

Either way, I recomend to stay with timestamp. 无论哪种方式,我都建议保留时间戳。

I see the field is called "DocumentID", perhaps you want to save a hash value as identifier? 我看到该字段称为“ DocumentID”,也许您想将哈希值保存为标识符? You can archieve this with virtual columns . 您可以使用虚拟列将其归档。 An example . 一个例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM