问题
I am creating a table in SSRS with Business Intelligence 2008. I have a date, as a string, as one of the values used in the table. This value may have a string representing a date, OR it could also be blank. If it has a value, I want the value formatted in a different way. Right now, I have this expression for the cell in which it is displayed:
=IIf(Fields!MyDate.Value = Nothing, "", Format(CDate(Fields!MyDate.Value), "dd-MM-yyyy"))
This works perfectly if the field has a value. However, when the field is blank, the cell is populated with #Error
. This would make sense if I just had the Format
function, but it seems like the IIf
should prevent it from trying to run that with a blank value. I tested it with this expression:
=IIf(Fields!MyDate.Value = Nothing, "No value", "Value")
...and sure enough the blank values entered the correct part of the statement and printed "No Value". I don't understand why the second part of the expression, which isn't used, would cause an error. Is there a way to rewrite this that will not cause an error? Thanks
EDIT: As I mentioned in the comments, I also tried a switch statement like this:
=Switch(Fields!MyDate.Value = Nothing, "", Fields!MyDate.Value <> Nothing, Format(CDate(Fields.MyDate.Value), "dd-MM-yyyy"))
However, this returned #Error
for blank values as well.
EDIT Regarding Possible Duplicate: PLEASE do not mark this as a duplicate to the question asking whether IIf short-circuits. I looked there, it asks a different question and does not give an answer that works for what I need.
回答1:
The problem is that Iif
does not short-circuit. One ugly workaround is to use a nested Iif
:
=IIf(Fields!MyDate.Value = Nothing, "", _
Format(CDate(Iif(Fields!MyDate.Value = Nothing, Today(),Fields!MyDate.Value)), "dd-MM-yyyy"))
Which is ugly, repetetive, and error-prone.
Another option is to create a custom function that does short-circuit:
Public Function FormatOrBlank (ByVal theDate As DateTime, ByVal format As String)
If String.IsNullOrWhiteSpace(theDate)
Return ""
Else
Return Format(CDate(theDate)), format)
End If
End Function
来源:https://stackoverflow.com/questions/37283287/ssrs-how-to-make-iif-statement-ignore-invalid-values