I am taking output from a view that has a column CreatedDate
which is returned in a dd/mm/yyyy
format. I want to filter output on behalf of date but nothing is showing up. Can anybody help me?
SQL Server code:
;with CTE as
(
select
CreatedDate,
UserID,
UserName,
SUM([CreditedAmount]) as CreditedAmount,
SUM([TDSPercent]) as TDSPercent,
SUM([TDSAmount]) as TDSAmount,
SUM(ISNULL([ApplicationServicePercentage], 0)) as ApplicationServicePercentage,
SUM(ISNULL([ApplicationServiceAmount], 0)) as ApplicationServiceAmount,
SUM([CreditedAmount]) - SUM([DebitedAmount]) - SUM(ISNULL([TDSAmount], 0)) - SUM(ISNULL([ApplicationServiceAmount], 0)) as AmountToPay
from
[dbo].[vwGetPaymentStatement]
where
[Status] = 0
and UserStatus = 1
group by
UserID, UserName, CreatedDate
)
select
CreatedDate,
UserID, UserName,
CreditedAmount, TDSPercent, TDSAmount,
ApplicationServicePercentage,
ApplicationServiceAmount,
AmountToPay
from
CTE
where
AmountToPay is not null
and (UserID = @uid or UserName like '%' + @username + '%')
and (CreatedDate between @datefrom and @dateto)
答案 0 :(得分:0)
Try casting to date if its not working?
(cast(CreatedDate as datetime) between @datefrom and dateto)
You hopefully already have your variables declared as datetime and dont need to cast those.
答案 1 :(得分:0)
根据您的评论和对其他答案的回答,我知道:
您的CreatedDate字段是VARCHAR
您的CreatedDate字段包含的数据不是正确的日期。
我首先运行CTE的定义,添加一个以帮助查找非日期值,如下所示:
select
CreatedDate,
UserID,
UserName,
SUM([CreditedAmount]) as CreditedAmount,
SUM([TDSPercent]) as TDSPercent,
SUM([TDSAmount]) as TDSAmount,
SUM(ISNULL([ApplicationServicePercentage], 0)) as ApplicationServicePercentage,
SUM(ISNULL([ApplicationServiceAmount], 0)) as ApplicationServiceAmount,
SUM([CreditedAmount]) - SUM([DebitedAmount]) - SUM(ISNULL([TDSAmount], 0)) - SUM(ISNULL([ApplicationServiceAmount], 0)) as AmountToPay
from
[dbo].[vwGetPaymentStatement]
where
[Status] = 0
and UserStatus = 1
and isdate(createddate) = 0 --- > Added this row to find the non-date values
group by
UserID, UserName, CreatedDate
一旦你弄清楚如何处理这些非日期值,你应该没问题。除非您对@datefrom和@dateto变量的数据类型有疑问。
答案 2 :(得分:0)
SELECT createddate,
userid,
username,
creditedamount,
tdspercent,
tdsamount,
applicationservicepercentage,
applicationserviceamount,
amounttopay
FROM cte
WHERE amounttopay IS NOT NULL
AND ( userid = @uid
OR username LIKE '%' + @username + '%' )
AND ( createddate BETWEEN CONVERT(VARCHAR, Cast(@datefrom AS DATETIME),
103) AND
CONVERT(VARCHAR, Cast(@dateto AS DATETIME
), 103)