gpt4 book ai didi

c# - 是否可以在 Microsoft SQL Server 中创建作为日期部分的列?

转载 作者:行者123 更新时间:2023-11-30 13:44:56 27 4
gpt4 key购买 nike

我想创建一个像这样的列:

create table dbo.t1
(
[Notification_Month] datepart(mm, [date]) null,
)

我想将月份存储为日期属性,而不存储日期的其他部分。我知道这是一个奇怪的问题,但是这个表正在被 WPF 应用程序使用,因此如果 SQL Server 允许的话,限制日期条目会更容易,但如果不允许,我可能可以使用 C# 找到一个冗长而复杂的解决方案。

如果这不可能,我有一些其他的变通办法,但在我说这不可能之前,我想过,总是最好检查一下堆栈。

最佳答案

虽然您仍然必须将 [date] 存储为 DATE 类型,但您可以使用计算列:

Create Table yourTable(
[NOTIFICATION_MONTH] DATE,
, [MONTH_NOTIFIED] as DATEPART(MONTH, [NOTIFICATION_MONTH])
)

添加 PERSISTED 会将其保存在表中。没有它,每次都会自动计算。

computed_column_expression 下的 MSDN CREATE TABLE 页面上:

Is an expression that defines the value of a computed column. A computed column is a virtual column that is not physically stored in the table, unless the column is marked PERSISTED. The column is computed from an expression that uses other columns in the same table. For example, a computed column can have the definition: cost AS price * qty. [...]

另一种选择是:

  • 用 tinyint 为月份创建一个表
  • 在您的表上创建一个带有日期的 View
  • 在 View 上创建触发器并按月替换日期
  • 插入带有日期的 View

关于c# - 是否可以在 Microsoft SQL Server 中创建作为日期部分的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33696755/

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