COALESCE db2 date - sql

I am trying to query on 2 different date fields and one date field (datefield2) has null values. My date field is CCYYDDD and I usually convert this to mm/dd/yyyy by date(digits(datefield)) as NewDate.
This fails
SELECT type, date(digits(datefield1)) AS DateEntered, coalesce(varchar(datefield2),'') as Renewed
FROM MYDATA
WHERE date(digits(datefeld1)) between '06/01/2015' and '6/30/2015' OR date(digits(coalesce(varchar(rendt7),''))) between '06/01/2015' and '06/30/2015'
The following succeeds
SELECT type, date(digits(datefield1)) AS DateEntered, coalesce(varchar(datefield2),'') as Renewed
FROM MYDATA
WHERE date(digits(datefeld1)) between '06/01/2015' and '6/30/2015' OR coalesce(varchar(rendt7),'') between '2015152' and '2015181
How can I query where my date fields contain null values? I plan on passing parameters in for the date range values and would rather just pass mm/dd/yyyy.

I'm a little confused by your question, but I think what you're really looking for is the TIMESTAMP_FORMAT function. I think it would be something like this:
SELECT
type
,DATE(TIMESTAMP_FORMAT(datefield1,'YYYYDDD')) AS DateEntered
,DATE(COALESCE(TIMESTAMP_FORMAT(datefield2,'YYYYDDD'),'0001-01-01')) AS Renewed
FROM MYDATA
WHERE DATE(TIMESTAMP_FORMAT(COALESCE(datefield1, rendt7),'YYYYDDD'))
BETWEEN #date1 AND #date2

Related

SQL: How To Select Earliest Date

I have a date column & I am simply trying to know the earliest date. I use the command:
select Min(Install_date) From PocketGemsSchema.pocketgemstable2;
This returns 1-Dec-17
But the minimum date from my sample data is actually 1-Nov-17.
Can anyone help please?
Try this:
If your Install_date contain datatype varchar than
SELECT MIN(CAST(Install_date AS DATE))
FROM PocketGemsSchema.pocketgemstable2
SELECT FORMAT(MIN(CAST(Install_dateAS DATE)), 'dd-MMM-yy ')
FROM PocketGemsSchema.pocketgemstable2
If your Install_date contain datatype date or datetime than your query will work
I think its the data type issue , you can try two approach
convert the field to datatime and your query should work
cast it on the run time like below
Mysql
SELECT Min(Str_to_date(Install_date, '%m/%d/%Y'))
FROM pocketgemsschema.pocketgemstable2;
SQL server
SELECT Min(Cast(Install_date as datetime))
FROM pocketgemsschema.pocketgemstable2;
I would change the column to a date or a datetime type and sort out any bugs that arise.

Convert/get varchar variable to YYYYMM

I have 4 CTE's in this table and the third one contains a DATETIME converted to VARCHAR (with format based on the requirement) as startDate in DD/MM/YYYY format. The last cte does calculations based on the data generated and one of the columns needs to store YYYYMM date based on startDate.
The problem it's getting the year and the month from this converted DATETIME, using convert() it shows this:
IDPER
-------
01/01/ --DD/MM/
These 2 show YYYYMM correctly when startDate isn't converted:
Select *, left(convert(nvarchar(6),new_ini,112),6) as IDPER from table
Select *, convert(nvarchar(6),new_ini,112) as IDPER from table
How could I get YYYYMM format having startDate converted? Or what could be a more smart approach to the requirement
If you have a string in the format DD/MM/YYYY and you want YYYYMM, then use string operations:
select right(new_ini, 4) + substring(new_ini, 4, 2)
You should be storing date values as dates or a related type, not as string. But given that you have already stored this as a string, string operations can do what you need.
My way would be slightly different
SELECT CONVERT(NVARCHAR(6), CONVERT(DATE, new_ini, 103), 112);
Here, I first converted it to date and then formatted to YYYYMMDD and taken 6 chars only
declare #date DATE = GETDATE();
select REPLACE(LEFT(CONVERT(DATE,#date,112),8),'-','') -- 1st approach
select FORMAT(#date,'yyyyMM') --2nd approach

SQL server 2012 error converting date from string when selecting date with like

In my table, I have a datetime NULL field called logDate.
The format stored: 2014-03-28 12:24:00.000
I have a form and the log date is one of the fields for searching logs.
The user will enter the date like 2014-03-28
So in my SELECT procedure I need to use a LIKE:
#logDate datetime =NULL
.
.
SELECT .. FROM mytable WHERE
(#logDate IS NULL OR CONVERT(VARCHAR, #logDate, 102) LIKE '%'+logDate+'%')
I execute the procedure:
EXEC dbo.SELECT_mytable #logDate= '2014-03-28'
But I get the following error:
Conversion failed when converting date and/or time from character string.
What am I doing wrong?
You also need to convert the logdate column to a varchar, I think you have your LIKE the wrong way around as you are trying to find the user entered date within the date column, so try:
SELECT .. FROM mytable WHERE
(#logDate IS NULL
OR '%'+CONVERT(VARCHAR, #logDate, 102)+'%' LIKE CONVERT(VARCHAR, logDate, 102))
As others have indicated (and I should have pointed out) you shouldn't be converting Dates to Strings in-order to search date columns, much better to keep everything in a DateTime format for performance.
This will work, provided that you change your stored procedure to expect the #logDate parameter as a DateTime:
SELECT .. FROM mytable WHERE
(#logDate IS NULL
OR logDate = #logDate)
I get the impression that you went down the string comparison route because you wanted to ignore the time element and just search on date, if that is the case you can strip the time from both elements and just match on date by doing this:
IF #logDate IS NOT NULL
BEGIN
// Remove any time element
SET #logDate = DATEADD(dd,0, DATEDIFF(dd,0,#logDate))
END
SELECT .. FROM mytable WHERE
(#logDate IS NULL
OR DATEADD(dd,0, DATEDIFF(dd,0,logDate)) = #logDate)

finding data lying between a specific date range in sql

I want to find records from my database which lie between any user input date range(say between 10/2/2008 to 26/9/2024). I tried using
SELECT NAME
,TYPE
,COMP_NAME
,BATCH_NO
,SHELF
,MFG_DATE
,EXP_DATE
,QTY
,VAT
,MRP
FROM STOCK_LOCAL
WHERE
convert(VARCHAR(20), EXP_DATE, 103)
BETWEEN convert(VARCHAR(20), #MEDICINEEXP_DATE, 103)
AND convert(VARCHAR(20), #MEDICINEEXPDATE, 103)
but with this query i need to enter perfect date range which is available in my database, it is not giving me data lying in between any date entered.
Thanks in advance
Since it is a poolr designed schema there isnt going to be any decent/Efficient solution for this.
In sql server if you are storing Date or Date & Time data. Use the Data or DATETIME datatypes for your columns.
In your case you are trying to compare a string with passed date. and even when you tried to convert the string (Date) into date datatype you didnt do it correctly.
My suggestion would be Add new columns to your table with Date datatype and update these columns with existing date/string values.
For now you can convert the Date(string) into date datatype using the following code.
DECLARE #MEDICINEEXP_DATE DATE = 'SomeValue1'
DECLARE #MEDICINEEXPDATE DATE = 'SomeValue1'
SELECT query....
FROM TableName
WHERE
CAST(
RIGHT(EXP_DATE, 4)
+SUBSTRING(EXP_DATE,CHARINDEX('/',EXP_DATE)+1,2)
+LEFT(EXP_DATE,2)
AS DATE) >= #MEDICINEEXP_DATE
AND CAST(
RIGHT(EXP_DATE, 4)
+SUBSTRING(EXP_DATE,CHARINDEX('/',EXP_DATE)+1,2)
+LEFT(EXP_DATE,2)
AS DATE) <= #MEDICINEEXPDATE
Note
This solution will get you the expected results but very inefficient method. It will not make use of any indexses on your EXP_DATE Column even if you have a very buffed up index on that column.

SQL: Convert String of MMMDD to Datetime

I have a nvarchar(5) column of data that is formatted MMMDD (for example, OCT26). With my select statement, I'd like to convert it to a datetime data type with the current year, and then save that datetime value as an alias, say, UsefulDate. So something like 10-26-2012.
Something like: SELECT (whatever SQL gets the job done) AS UsefulDate
The exact formatting doesn't matter; I just need to be able to compare two dates together with greater than and less than operators. Also, sometimes the column will be blank. In that case, I'd like to set the alias to blank as well. Is this possible?
Thanks for your help!
You can convert varchar fields in format MMMDD to date with current year with :
select convert(datetime,'OCT26'+','+cast(year(getdate()) as varchar),107)
So your query would be something like :
select convert(datetime,case varcharDate when '' then null else varcharDate end +
','+cast(year(getdate()) as varchar),107) as UsefulDate
from table
select CASE WHEN ISDATE(mmmdd+' '+right(year(getdate()),4)) = 1
THEN CAST(mmmdd+' '+right(year(getdate()),4) as datetime)
END UsefulDate, *
from tbl