简体   繁体   中英

return rows from 30 days ago in sql tables

I want to fetch up rows of two tables from 30 days ago in sql but my date column is nvarchar and I cant convert it to date I tried several things but But did not receive any result and And always got an error

this is my query and I send TodayTime parameter from program by @Date to 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

my problem is here

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

Date Column in Tables and @Date Format => 2017/02/02

After execute this procedure , This error will be displayed :

The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.

Please Guide Me

Thank you very much

@date should really be a date data type instead (or datetime , or datetime2 ). Using n/varchar for dates is a bad decision.

/* 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM