MSSQL DateTime2 更新失败
Posted
技术标签:
【中文标题】MSSQL DateTime2 更新失败【英文标题】:MSSQL DateTime2 Fail to Update 【发布时间】:2016-07-27 07:06:09 【问题描述】:我正在运行存储过程,它负责插入、更新和删除表的条目。
虽然插入和删除都运行顺利,但更新操作会更新除DATETIME2
之外的所有列。
场景 - 我通过以下方式测试我的存储库模式(使用 C# 代码):
-
删除整个
[BackgroundTaskAttachtment]
表
创建 4 个新条目
删除在第 2 步创建的单个条目
等待 5 秒
修改其中一项
结果是[BackgroundTaskAttachtment]
表中有 3 个条目,所有属性都按预期设置,除了未更新的 [UpdatedOnUtc](它等于 [CreatedOnUtc]
我标记了更新的行(如您所见[FilePath]
已成功更新):
非常感谢社区见解,
谢谢
这是存储过程代码:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[SP_ArrangeBackgroundTaskAttachtments]
(
@backgroundTaskId BIGINT,
@taskAttchs [dbo].[BackgroundTaskAttachtmentType] READONLY
)
AS
BEGIN
SET NOCOUNT ON;
--delete all removed attachtments
DELETE FROM [BackgroundTaskAttachtment]
WHERE [BackgroundTaskId] = @backgroundTaskId AND [Id] NOT IN (SELECT [Id] FROM @taskAttchs)
----Update exist key-value pairs
UPDATE [dbo].[BackgroundTaskAttachtment]
SET
[IsPrimary] = attachs.[IsPrimary],
[FilePath] = attachs.[FilePath],
[Bytes] = attachs.[Bytes],
[UpdatedOnUtc] = GETUTCDATE()
FROM @taskAttchs AS attachs
WHERE attachs.[Id] = [BackgroundTaskAttachtment].[Id]
--insert new records
SELECT @backgroundTaskId AS [BackgroundTaskId], [FilePath], [IsPrimary], [Bytes], GETUTCDATE() AS [CreatedOnUtc], GETUTCDATE() AS [UpdatedOnUtc]
INTO #Temp FROM @taskAttchs as atcs
WHERE atcs.[Id] NOT IN (SELECT [Id] FROM [BackgroundTaskAttachtment] AS bta WHERE bta.[BackgroundTaskId] = @backgroundTaskId )
INSERT INTO [BackgroundTaskAttachtment]([BackgroundTaskId], [IsPrimary], [Bytes], [FilePath], [CreatedOnUtc], [UpdatedOnUtc] )
SELECT [BackgroundTaskId], [IsPrimary], [Bytes], [FilePath], [CreatedOnUtc], [UpdatedOnUtc]
FROM #Temp
END
这是表类型(从 CLR 发送到 SQL)
CREATE TYPE [dbo].[BackgroundTaskAttachtmentType] AS TABLE(
[Id] [BIGINT] NOT NULL,
[FilePath] [NVARCHAR](MAX) NULL,
[IsPrimary] [BIT] NOT NULL,
[BackgroundTaskId] [BIGINT] NULL,
[Bytes] [VARBINARY](MAX) NULL
)
GO
这是表定义
CREATE TABLE [dbo].[BackgroundTaskAttachtment]
(
[Id] BIGINT IDENTITY(1,1) NOT NULL,
[BackgroundTaskId] BIGINT NOT NULL,
[IsPrimary] BIT NOT NULL DEFAULT 0,
[FilePath] NVARCHAR(MAX) NULL,
[Bytes] VARBINARY(MAX) NULL,
[CreatedOnUtc] DATETIME2 NOT NULL,
[UpdatedOnUtc] DATETIME2 NOT NULL,
[RowVersion] ROWVERSION NOT NULL,
CONSTRAINT [PK_dbo.BackgroundTaskAttachtment] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_dbo.BackgroundTaskAttachtment_BackgroundTask_Id]
FOREIGN KEY ([BackgroundTaskId])
REFERENCES [dbo].[BackgroundTask] ([Id])
ON DELETE CASCADE
);
【问题讨论】:
【参考方案1】:请尝试使用返回datetime2
的SYSUTCDATETIME
。
您正在使用的GETUTCDATE
返回datetime
。
【讨论】:
不 - 它没有帮助 - 仍然有同样的问题以上是关于MSSQL DateTime2 更新失败的主要内容,如果未能解决你的问题,请参考以下文章
将 datetime2 数据类型转换为 datetime 数据类型导致值超出范围
(MSSQL)sp_refreshview刷新视图失败及更新Table字段失败的问题解决
强制实体框架使用 datetime 而非 datetime2