Why can't I use a datetime parameter in ssrs?

喜你入骨 提交于 2019-12-24 16:57:18

问题


I have an SSRS Date/Time parameter generated from a shared dataset query against a SQL Server datetime field. The parameter displays correctly in a report textbox but it will not work in an embedded dataset query, even against the same table that the datetime value was generated from.

In order to use the parameter for a dataset query I have to parse both sides of a where clause to get it to work in Preview in SSDT:

(convert(varchar,invoice.snapshot_datetime,120)) = (convert(varchar,@snapshotdatetime,120))

This is tremendously inefficient.

How can I get my where clause to work without parsing the invoice.snapshot_datetime column?

Server Details

  • The SQL Server Language is English (United States).
  • SQL Server dateformat is mdy (from dbcc useroptions).
  • Getdate() returns '2015-05-20 10:27:56.687' in SSMS

回答1:


Assuming your date range is between 1900-01-01 and 2079-06-06 you can cast to SmallDateTime to truncate the seconds out of your datetime variable:

DECLARE @DateTime datetime
SET @DateTime = CAST(CAST(@snapshotdatetime as SmallDateTime) as DateTime)

(thanks to t-clausen.dk for his answer here)

Now, since your actual column is of type DateTime, it does keep seconds (and milliseconds), and you will need to eliminate them as well.
However, using functions on your column will prevent the SQL Server from using any indexes you might have on this column, so a better approach would be to use a DateTime range:

DECLARE @FromDateTime datetime, @ToDateTime datetime
SET @FromDateTime = CAST(CAST(@snapshotdatetime as SmallDateTime) as DateTime)

Since the cast will round the minutes of the small date time up if it's over 29.998 seconds, and down if it's below 29.999 seconds. You always want to round down since it's From datetime, you need to cheke if you need to decrease a minute:

IF datepart(second, @snapshotdatetime) > 29 
OR (datepart(second, @snapshotdatetime) = 29 
    AND datepart(millisecond, @snapshotdatetime) > 998)
SET @FromDateTime = DATEADD(minute, -1, @FromDateTime)

SET @ToDateTime = DATEADD(minute, 1, @FromDateTime)

and then, in your where clause, use this:

invoice.snapshot_datetime <= @FromDateTime 
AND invoice.snapshot_datetime >= @ToDateTime



回答2:


If you haven't found solution yet, try this:

select (convert(varchar,GETDATE(),112))

it will return 20180206 (yyymmdd)



来源:https://stackoverflow.com/questions/30344543/why-cant-i-use-a-datetime-parameter-in-ssrs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!