尝试从数据类型bigint转换为日期时出错

时间:2019-04-27 19:39:59

标签: sql sql-server tsql sql-server-2008 stored-procedures

我已更改数据库中的表以添加新列{ $lookup: { from: "users", let: { subscribers: "$subscribers" }, pipeline: [ { $match: { $expr: { $in: ["$_id", "$$subscribers"] }}}, { $project: { status: 1, personal_info: 1 }} ], as: "subscribers" } },

subscribers

现在我在新列LogDate中得到的结果看起来像ALTER TABLE AccountsTable ADD LogDate bigint NOT NULL DEFAULT(0) GO

之后,我尝试更改登录过程并添加了以下代码:

LogDate

在尝试使用上面的代码更改登录过程时,出现以下错误:

  

不允许从数据类型bigint到日期的明确转换。

感谢您对我可以解决该问题的任何帮助。我正在使用SQL Server 2008。

1 个答案:

答案 0 :(得分:1)

试图找出问题所在

主要问题是您试图将bigint值强制转换为不允许的日期。

CAST(LogDate as Date)

将抛出以下表达式:

  

不允许从数据类型bigint到日期的明确转换。

即使整数采用以下格式,yyyyMMdd,例如:19700101

如果整数值采用以下格式yyyyMMdd,则可以将ot字符串转换为日期

CAST(CAST(LogDate as varchar(25)) as Date)

否则,您必须实现自己的逻辑。例如,如果该列包含与1970-01-01的第二个差异,则可以使用:

DATEADD(s, [LogDate], '19700101')

此外,使用以下表达式

[LogDate] = GetDATE()

将导致以下异常:

  

不允许从数据类型datetime到bigint的隐式转换。使用CONVERT函数运行此查询。

您必须将其更改为

[LogDate] = DATEDIFF(s, '19700101', GETDATE()) 

OR

[LogDate] = CAST(GETDATE() as BIGINT)

这取决于您的需求


日期类型转换

从下面的Microsoft Grid中,您可以看到每种方法可以转换哪些数据类型:

enter image description here

参考


更新-修正代码逻辑

根据您的评论,我认为您正在寻找以下逻辑:

UPDATE [dbo].[AccountsTable] 
SET LogDate = DATEDIFF(s, '19700101', GETDATE()) 
WHERE AccID = @id AND LogDate IS NULL

UPDATE [dbo].[AccountsTable]
SET ConsecutiveDays = 
    CASE
       WHEN  ConsecutiveDays  > 3 
          THEN 1
       WHEN  CAST(DATEADD(s, [LogDate], '19700101') AS DATE) < CAST(DATEADD(d,(-1 * [ConsecutiveDays]),GETDATE()) AS DATE)
          THEN 1
       WHEN  CAST(DATEADD(s, [LogDate], '19700101') AS DATE) < CAST(GETDATE() AS DATE)
          THEN ConsecutiveDays + 1 
       ELSE ConsecutiveDays  
    END,
    ChallengesCompleted = 
        CASE 
           WHEN ConsecutiveDays = 3
           THEN ChallengesCompleted + 1
           ELSE ChallengesCompleted
        END,
    LogDate = DATEDIFF(s, '19700101', GETDATE())
WHERE 
    AccID = @id

更新2-基于聊天讨论

尝试使用以下代码:

UPDATE [dbo].[AccountsTable] 
SET LogDate = DATEDIFF(s, '19700101', GETDATE()) 
WHERE AccID = @id AND LogDate IS NULL

UPDATE [dbo].[AccountsTable]
SET ConsecutiveDays = 
    CASE
       WHEN  ConsecutiveDays  >= 3 
          THEN 1
       WHEN  CAST(DATEADD(s, [LogDate], '19700101') AS DATE) < CAST(DATEADD(d,(-1 * [ConsecutiveDays]),GETDATE()) AS DATE)
          THEN 1
       WHEN  CAST(DATEADD(s, [LogDate], '19700101') AS DATE) < CAST(GETDATE() AS DATE)
          THEN ConsecutiveDays + 1 
       ELSE ConsecutiveDays  
    END,
    ChallengesCompleted = 
        CASE 
           WHEN ConsecutiveDays = 2 
                AND CAST(DATEADD(s, [LogDate], '19700101') AS DATE) = CAST(DATEADD(d,(-1 * [ConsecutiveDays]),GETDATE()) AS DATE)
           THEN ChallengesCompleted + 1
           ELSE ChallengesCompleted
        END,
    LogDate = DATEDIFF(s, '19700101', GETDATE())
WHERE 
    AccID = @id