【问题标题】:return rows from 30 days ago in sql tables在 sql 表中返回 30 天前的行
【发布时间】:2017-02-24 20:45:15
【问题描述】:

我想在 sql 中获取 30 天前的两个表的行 但我的日期列是 nvarchar,我无法将其转换为日期 我尝试了几件事,但没有收到任何结果,而且总是出错

这是我的查询和 我通过 @Date 将 TodayTime 参数从程序发送到 sql

[dbo].[Report30Days]
@Date nvarchar(10)
as

select
    coalesce(S.Date,B.Date) Date,
    coalesce(S.TAccount,0) sTAccount,
    coalesce(S.Remaining,0) sRemaining,
    coalesce(B.TAccount,0) bTAccount,
    coalesce(B.Remaining,0) bRemaining
from
    (select
        Date,sum(TAccount) TAccount, sum(Remaining) Remaining
    from SaleInvoices
    where
        DateDiff(day,convert(datetime,@Date,110),convert(datetime,Date,110))<=30
    group by Date) S
    Full Outer Join
    (select
         Date,sum(TAccount) TAccount, sum(Remaining) Remaining
    from BuyInvoices
    where
        DateDiff(day,convert(datetime,@Date,110),convert(datetime,Date,110))<=30
    group by Date ) B
    on
        S.Date=B.Date

我的问题来了

where
        DateDiff(day,convert(datetime,@Date,110),convert(datetime,Date,110))<=30

表格中的日期列和@Date 格式 => 2017/02/02

执行此程序后,将显示此错误:

将 nvarchar 数据类型转换为 datetime 数据类型导致值超出范围。

请指导我

非常感谢

【问题讨论】:

  • 您得到的确切错误是什么?还有,Date的数据类型是什么?
  • 为什么需要将今天的日期作为参数传递给存储过程?您可以在 SQL 脚本中获取今天的日期。还有,为什么一定要把参数类型定义为nvarchar?
  • 你能用一个不那么模棱两可的日期例子吗?像 12 月 31 日?
  • 尝试将字符串传递为 '2017-02-02'

标签: sql sql-server sql-convert


【解决方案1】:

@date 实际上应该是 date 数据类型(或 datetimedatetime2)。使用 n/varchar 作为日期是一个错误的决定。

/* lets make a proper date parameter */
/* @date nvarchar format is  YYYY/MM/DD, replacing / gives us YYYYMMDD 
   which sql server can easily convert to a date    */
declare @ActualDate date;
set @ActualDate = dateadd(day,-30,convert(date,replace(@date,'/','')));

select
    coalesce(S.Date,B.Date) Date,
    coalesce(S.TAccount,0) sTAccount,
    coalesce(S.Remaining,0) sRemaining,
    coalesce(B.TAccount,0) bTAccount,
    coalesce(B.Remaining,0) bRemaining
from
    (select
        Date,sum(TAccount) TAccount, sum(Remaining) Remaining
    from SaleInvoices
    where convert(date,replace(Date,'/','')) => @ActualDate
    group by Date
    ) S
    Full Outer Join
    (select
         Date,sum(TAccount) TAccount, sum(Remaining) Remaining
    from BuyInvoices
    where convert(date,replace(Date,'/','')) => @ActualDate
    group by Date 
    ) B
    on S.Date=B.Date

【讨论】:

  • 对不起,表中的日期列也是 nvarchar 并且在执行时仍然显示错误
  • @MPersia 已更新...为什么您的所有日期都存储为文本?
  • 那么如何在sql中使用shamsi日历呢?直到此时,这对我来说都很舒服
  • @MPERSIA 啊,我明白了。这会让事情变得更加困难。
  • 但这次我被困在了这个问题上
猜你喜欢
  • 1970-01-01
  • 2017-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多