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

Is it possible in Microsoft SQL Server to create a column that is a datepart?

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

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

我想将月份存储为日期 属性,而不存储日期的其他部分。我知道这是一个奇怪的问题,但是这个 table 正在被 WPF 应用程序使用,所以如果 SQL 服务器允许这个,那么限制日期条目会更容易,但如果不允许,我可能会发现一个冗长而复杂的问题使用 c# 的解决方案。

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

尽管您仍然需要将 [date] 存储为 DATE 类型,但您可以使用计算列:

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

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

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. [...]

另一种选择是:

  • 创建一个 table 带有 tinyint 的月份
  • 在您的 table 上创建一个带有日期
  • 的视图
  • 在视图上创建触发器并按月替换日期
  • 插入带有日期的视图