Why converting varchar field to date is not working? - sql

Select v.VendorCode VendorCode, V.VendorName
where
vi.Vendor_ID= 154
and
vi.Company_ID= (Select CompanyID from Company where CompanyID= '2')
AND
( Cast(vi.InvoiceDate as date) between Cast('3/1/2011' as date)
AND cast('3/29/2018' as date)
)
when I include the date part.. it doesn't return result. InvoiceDate is saved as varchar in table and is saving dates like 1/22/2019.
I cannot change the type becuase it's the legacy database and has to be changed in thousand places.

You may not be able to change the data in the database, but you can at least get in the habit of using proper date formats for your queries.
First, use convert with format 101 for the conversion. Use try_convert() if anyone got the date wrong.
Second, use 'YYYYMMDD' or 'YYYY-MM-DD' for date constants:
try_convert(date, v.InvoiceDate, 101) between '20110301' and '20180329'
Finally, you can add a computed column, so you can start to migrate to better code:
alter table v add InvoiceDate_Date as (try_convert(date, vi.InvoiceDate, 101));
Then you can write the logic as:
InvoiceDate_date between '20110301' and '20180329'

To debug, try to see what the DBMS sees when filtering by date:
Select
v.VendorCode
, v.VendorName
, cast(vi.InvoiceDate as date) as InvoiceDate
, cast('3/1/2011' as date) as FromDate
, cast('3/29/2018' as date) as ToDate
from ...
where
vi.Vendor_ID = 154
and vi.Company_ID= (Select CompanyID from Company where CompanyID= '2')

Related

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

How to convert date format in string using SQL query?

I am using ASP.NET MVC with petapoco. I want to display data from database table in the view as it has date column and I want to convert that date format in varchar like 'dd-mm-yyyy'.
My date column is TransactionDate.
My query is as follows, I have used convert function, but it is not working, my date column is still appearing with milliseconds like /Date152235232/.
Please help me with this and tell me how I can convert that particular TransactionDate column in the table to display date in the 'dd-mm-yyyy' format.
var sql = db.Query("Select CONVERT(varchar, d.TransactionDate ,101), d.DocumentId, d.SurveyNumber, d.FullName, d.Location, documenttype.DocumentTypeName, d.VillageName, d.PlanNumber, d.OwnerName, d.ContactNumber, d.Email, d.Status, d.TransactionDate FROM Document d " +
$"INNER JOIN DocumentType ON d.DocumentTypeId = documenttype.DocumentTypeId");
Here in the query I am joining two tables to fetch data from the table to display it
Try this: 105 will give you format dd-mm-yyyy: https://www.itsupportguides.com/knowledge-base/sql-server/sql-how-to-convert-datetime-to-formatted-date-string-dd-mm-yyyy/
CONVERT( VARCHAR, d.TransactionDate, 105 )
If your filed is date type and you want formatting dd-mm-yyyy then
you should have to use
select CONVERT (varchar(10), getdate(), 105)
return :15-08-2018
but if you want dd/mm/yyyy then you have to use below
CONVERT(VARCHAR(20), getdate(), 103) as date_conv
15/08/2018
more about date format
Your query is returning the date twice. Perhaps this will do what you want:
select convert(varchar(10), d.TransactionDate, 105) as TransactionDate,
d.DocumentId,
d.SurveyNumber,
d.FullName,
d.Location,
dt.DocumentTypeName,
d.VillageName,
d.PlanNumber,
d.OwnerName,
d.ContactNumber, d.Email,
d.Status
from Document d join
DocumentType dt
on d.DocumentTypeId = dt.DocumentTypeId;
Note the original TransactionDate has been removed from the query. I also added a table alias for DocumentType.

SQL Server: how to select records with specific date from datetime column

I have a table with one column dateX formatted as datetime and containing standard dates.
How can I select all records from this table where this dateX equals a certain date, e.g. May 9, 2014 ?
I tried the following, but this returns nothing even if I have several records with this date.
SELECT *
FROM dbo.LogRequests
WHERE (CONVERT(VARCHAR(10), dateX, 101) = '09/05/14')
Edit: In the database the above example looks as follows, using SQL 2012: 2014-05-09 00:00:00.000
The easiest way is to convert to a date:
SELECT *
FROM dbo.LogRequests
WHERE cast(dateX as date) = '2014-05-09';
Often, such expressions preclude the use of an index. However, according to various sources on the web, the above is sargable (meaning it will use an index), such as this and this.
I would be inclined to use the following, just out of habit:
SELECT *
FROM dbo.LogRequests
WHERE dateX >= '2014-05-09' and dateX < '2014-05-10';
For Perfect DateTime Match in SQL Server
SELECT ID FROM [Table Name] WHERE (DateLog between '2017-02-16 **00:00:00.000**' and '2017-12-16 **23:59:00.999**') ORDER BY DateLog DESC
SELECT *
FROM LogRequests
WHERE cast(dateX as date) between '2014-05-09' and '2014-05-10';
This will select all the data between the 2 dates

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: retrieve records between dates in all databases

I would like to select all the records in a table between two dates. I have a query like:
SELECT * FROM <table> WHERE (thedate BETWEEN DATE('2012-04-01') AND DATE('2012-06-30'))
This is fine for HSQL, Oracle, PostgreSQL, but it doesn't work in SQL Server due to the lack of the Date function. Is there a way to get this to work generally for all databases (including SQL Server) or do I need to use an ORM like Hibernate (I know I should, but I'm specifically asking if this can be done in SQL)?
There's no need for the Date(...) as far as i can tell. This example seems to work
DECLARE #TheDate Date = '2012-07-01';
SELECT 'hello' WHERE (#TheDate BETWEEN '2012-04-01' AND '2012-06-30')
--None returned
SET #TheDate = '2012-05-01'
SELECT 'hello' WHERE (#TheDate BETWEEN '2012-04-01' AND '2012-06-30')
--selects hello
Edit Btw worth looking at This Question with the date time answer (will post here just to save effort)
The between statement can cause issues with range boundaries for dates as
BETWEEN '01/01/2009' AND '01/31/2009'
is really interpreted as
BETWEEN '01/01/2009 00:00:00' AND '01/31/2009 00:00:00'
so will miss anything that occurred during the day of Jan 31st. In this case, you will have to use:
myDate >= '01/01/2009 00:00:00' AND myDate < '02/01/2009 00:00:00' --CORRECT!
or
BETWEEN '01/01/2009 00:00:00' AND '01/31/2009 23:59:59' --WRONG! (see update!)
UPDATE: It is entirely possible to have records created within that last second of the day, with a datetime as late as 01/01/2009 23:59:59.997!!
For this reason, the BETWEEN (firstday) AND (lastday 23:59:59) approach is not recommended.
Use the myDate >= (firstday) AND myDate < (Lastday+1) approach instead.
in sql-server I think you may want to look into the
DATEADD ( datepart , number, date )
DATEDIFF ( datepart , startdate , enddate )
but I think you're looking for
CAST ( expression AS data_type )
or
CONVERT ( data_type [ ( length ) ] , expression [ , style ] )
usage:
Select * from myTable where thedateToCompare >= CONVERT ( datetime , "dd/mm/yy hh:mi:ss:mmmAM" ) and thedateToCompare <= CONVERT ( datetime , "dd/mm/yy hh:mi:ss:mmmAM" )
something that may change your approach is weather your source 'thedate' column type datetime, smalldatetime or is it stored in a column defined as string?
You may want to check out a link! for more detial on datetime constants that you could use for your string variations.