0

我想在 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 数据类型导致值超出范围。

请指导我

非常感谢

4

1 回答 1

1

@date实际上应该是一种date数据类型(或datetime,或datetime2)。使用 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
于 2017-02-24T21:00:00.870 回答