2017-02-24 39 views
0

我想從30天前在sql 中獲取兩個表的行,但我的日期列是nvarchar,我不能將它轉換爲日期 我嘗試了幾件事但不收到任何結果,並且並始終得到了一個錯誤從30天前在SQL表中返回行

這是我的查詢和 我通過@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年2月2日

之後執行該過程時,將顯示該錯誤:

一個nvarchar數據類型到datetime數據類型轉換導致超出範圍的價值。

請指導我

非常感謝您

+0

你正在得到什麼確切的錯誤?另外,「Date」的數據類型是什麼? –

+0

爲什麼你需要將今天的日期作爲參數傳遞給存儲過程?您可以在SQL腳本中獲取今天的日期。另外,爲什麼你必須將參數類型定義爲nvarchar? – Sparrow

+0

您可以使用較不明確的日期示例嗎?像12月31日? – SqlZim

回答

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 
+0

請原諒,表中的日期列也是nvarchar 仍然顯示執行時出錯 – MPERSIA

+0

@MPersia更新...爲什麼所有日期都以文本形式存儲? – SqlZim

+0

那我該如何在sql中使用shamsi calender? 這很舒服,直到這個時候 – MPERSIA