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

标签 c# sql-server create-table datepart

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

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/

相关文章:

c# - 如何检查 AttachedFlyout 是否打开

c# - 参数数量可变的扩展方法

c# - 我怎样才能使 Byte[] 可以为空

mysql - 如何创建一个表作为另一个表的副本并替换一个语句中列的值

php - 简单 : creating tables in database

c# - 防止在没有 page.redirect 的情况下重新发送表单

C# WebClient DownloadProgressChanged 无法正常工作

sql-server - 使用表变量时,公用表表达式变慢

sql - 如何检查 SQL 结果是否包含换行符?

database - Rails 创建一个没有迁移的表