Optional DateTime Parameter in SQL - sql

I have set up an SQL Stored Procedure where the parameters are optional as in the front end any combination of these filters can have values or not have values. The only problem is when I come pass a null date in. SQL produces an error if I leave this null, however I have managed to do some reading around the problem and found that using the following should resolve the error:
SET #SessionStarted = ISNULL(#SessionStarted, GETDATE())
Which it does however, now it's not returning records it should be returning because it's only looking for records with the current date and time.
The parameter is defined as such:
#SessionStarted datetime = NULL,
And the where clause for this particular parameter is:
(#SessionStarted IS NULL OR VisitDate = #SessionStarted)
Is there anyway round this issue when a value for the can't be specified?

You could just use a different date in your isnull and detect it. Something like '1900-01-01' feels like a good "known invalid" day to use in place of your NULL.

When you assign current date time to a variable (like below)
SET #SessionStarted = ISNULL(#SessionStarted, GETDATE())
and compare it (like below) against a datetime dattyped column, which will never equal and will not return records.
(#SessionStarted IS NULL OR VisitDate = #SessionStarted)
You should make sure that what value your datetime column holds and what is your expected default value to be assigned to the variable in case NULL value is passed in.

Related

How do I use LIKE with a date field in MS Access with a NULL value

I have an application that allows partial date searches. It doesn't specify what the date part is. if someone puts in "20", it could be part of the year or a day of the month.
The application uses an Access databases where some of the date fields have NULL values.
I am trying to write a query with [date field] LIKE {date criteria}.
What I started to do is convert the date field to a string using cstr(datefield), but the NULL values are giving #error values.
SELECT * ,cstr(datefield) AS strdate FROM table1
Access has the ISNULL function, but it only takes one parameter which returns true or false, as opposed to the ISNULL function in SQL Server, which takes two parameters, the second being the value to use if the first parameter is null.
I supposed I could add "AND datefield IS NOT NULL" to the end, but I wanted to ask if there were any other possible solutions to this.
Then when I did finally get to the query itself, it didn't return any results.
SELECT * ,cstr(datefield) AS strdate
FROM table1
WHERE scan_date IS NOT NULL
AND cstr(datefield) LIKE '%20%'
How would I do a LIKE query against a date field in access?
You can use the function Nz():
SELECT * , Nz(datefield) AS strdate
FROM table
WHERE Nz(datefield) LIKE '*20*'
But you should know that the wildcard operator to use in Access is not % but * and this is the reason that you don't get any results.

PSQL function help - date format issue

Just trying to clean up some functions someone else has done in a postgres.
Would anyone know what the following does? It was working, but the date format changed when it started coming in as '1999-09-07 16:30:00.000'
I don't know what the previous format was.
select
case
when dbDate = '' then null
when dbDate != '^\d.*' then dbDate::timestamp
else '1900-01-01'::date + dbDate::int
end as dbDate
Whenever I call the function with the date it gives me
invalid input syntax for integer: "1999-09-07 16:30:00.000"
This nice function was taking multiple kinds of date inputs and normalizing them.
I assume it expected one of:
blank which it let be null
a date starting with 'MMM' in date format which would not pass '^\d.*' (i.e. something that doesn’t start with a number) which it would cast as a date
a number
The reason that the date was being casted as an INT is because after failing the first two tests the person writing this was expecting an INT. They wanted to add the integer to the beginning of Time (i.e. 1900-01-01) like Excel does.
1999-09-07 16:30:00.000 fails the second test even though it could be cast as time.
This passes through to the else, which fails to cast it as INT, and throws the error.
In this case, you need to change your second test. Make it something that will allow a datetime that you have coming in, but that would reject a number that should be added to 1900-01-01.
If you don’t think you will have numbers coming in that should be added to 1900-01-01, then just get rid of the third test and use
select
case
when dbDate = '' then null
else dbDate::timestamp
end as dbDate

SQL Server ISDATE() Error

I have a table and need to verify that a certain column contains only dates. I'm trying to count the number of records that are not follow a date format. If I check a field that I did not define as type "date" then the query works. However, when I check a field that I defined as a date it does not.
Query:
SELECT
count(case when ISDATE(Date_Field) = 0 then 1 end) as 'Date_Error'
FROM [table]
Column definition:
Date_Field(date, null)
Sample data: '2010-06-27'
Error Message:
Argument data type date is invalid for argument 1 of isdate function.
Any insight as to why this query is not working for fields I defined as dates?
Thanks!
If you defined the column with the Date type, it IS a Date. Period. This check is completely unnecessary.
What you may want to do is look for NULL values in the column:
SELECT SUM(case when Date_Field IS NULL THEN 1 ELSE 0 end) as 'Date_Error' FROM [table]
I also sense an additional misunderstanding about how Date fields, including DateTime and DateTime2, work in Sql Server. The values in these fields are not stored as a string in any format at all. They are stored in a binary/numeric format, and only shown as a string as a convenience in your query tool. And that's a good thing. If you want the date in a particular format, use the CONVERT() function in your query, or even better, let your client application handle the formatting.
ISDATE() only evaluates against a STRING-like parameter (varchar, nvarachar, char,...)
To be sure, ISDATE()'s parameter should come wrapped in a cast() function.
i.e.
Select isdate(cast(parameter as nvarchar))
should return either 1 or 0, even if it's a MULL value.
Hope this helps.
IsDate takes a character string or exression that yeilds a character string as it's argument
The problem is this method ISDATE() only admits arguments of type datetime and smalldatetime within the "time" types, so it won´t work if you are using date type.
Also if you use date as type for that field, you won´t have to check the information there because it won´t admit other type of field.
You shoul only check for null values in your column, that´s all.

TSQL derived column with date convert that checks for non-date convertible strings

I have a date column with dates stored as strings, such as 20120817. Unfortunately, the text form field that populates this column is free text, so I cannot guarantee that an occasional "E" or "whatever" shows up in this column. And more than a few already have.
What I need to do is convert the string column into a date column. Of course the convert will reject the random string characters. Is there any way to create a derived column that will not only convert the strings but exclude the non-date convertible strings?
If there were no non-date convertible strings in the table, the following would work:
ADD [convertedDate] AS CONVERT(DATE, [stringDate], 102)
And it does work perfectly in a test table I created. But when I introduce other non-convertible strings, I receive the dreaded "Conversion failed when converting date and/or time from character string" error for obvious reasons.
Is there a function that will catch non-convertible elements that I can add on to this derived column code? Or is a view or function the only - or best - way to handle this? I played around with IsDate() with little luck.
Thank you!
There's a function called ISDATE(date), maybe you can use it in a CASE statement or in the WHERE part of the query... It depends on how you're doing it, maybe something like this
ADD [convertedDate] AS CASE WHEN ISDATE([stringDate]) = 1 THEN CONVERT(DATE,[stringDate], 102) ELSE NULL END
If you're using SQL Server 2012 you can make use of the try_convert function
http://msdn.microsoft.com/en-us/library/hh230993.aspx
It will work normally if the conversion succeeds but return null if the conversion fails
ADD [convertedDate] AS TRY_CONVERT(DATE, [stringDate], 102)
This should give you some ideas...
DECLARE #date1 varchar(50)
DECLARE #date2 varchar(50)
SET #date1 = '20120101'
SET #date2 = 'e20120101'
SELECT
ISDATE(#date1),
ISDATE(#date2),
CASE WHEN ISDATE(#date1) = 1 THEN CONVERT(SMALLDATETIME,#date1) END,
CASE WHEN ISDATE(#date2) = 1 THEN CONVERT(SMALLDATETIME,#date2) END

Converting SQL Server null date/time fields

Whenever the value is null for this query
SELECT ISNULL(someDateTime,'')
FROM someTable
the result is
someDateTime
------------
1900-01-01 00:00:00.000
I want it to be "No", so if I run this:
SELECT ISNULL(someDateTime,'No')
FROM someTable
then there's this error:
Conversion failed when converting datetime from character string.
How to do it? Thanks in advance!
The result of the expression will need to be a single type. If you want a character string (and you do, since 'No' is not a DateTime), you'll need to convert the datetime to such a string:
SELECT ISNULL(cast(someDatetime as varchar(20)), 'No') FROM someTable
As others have suggested, though, code like this smells bad, and you may want to pass the null to a client component and do the conversion there.
isnull() is trying to convert the second argument to the datatype of the field you specify in the first argument.
If you are going to be returning a string you need to cast the DateTime field to a string type so that isnull() can work properly - see Michael Petrotta's answer for a way to accomplish this.
You're still selecting a DateTime column, and so the result of that expression still needs to be a DateTime value rather than a string. To suggest an appropriate work-around, we'll need to know more about what you're really trying to do with this data.
You can't as such directly. It's easier to trap NULL in the client and change it to "no" there.
However, you could use a token value such as "17530101" which is a valid datetime, or CONVERT SomeDateTime first to varchar.
Otherwise, we need more info on why etc
In your Update Stored Proc: Update your previous date value to a new Null value:
.Parameters.AddWithValue("#Date_Value", Nothing).IsNullable = True