How to convert date format in string using SQL query? - sql

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.

Related

Why converting varchar field to date is not working?

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')

SQL Server : searching between dates in string data type

I have a table, which stores dates as type varchar.
In the SELECT statement, I want to extract ALL values of the table, but filter the data BETWEEN two dates.
I have tried converting and this is the closest I have gotten. any help would be appreciated. The dates I want to filter by is called opened
SELECT *
FROM table
WHERE Opened BETWEEN CONVERT(DATETIME, '01/08/2006', 103)
AND CONVERT(DATETIME, '01/05/2020', 103)
I would discourage you from using between with dates. Here is a good explanation of why, provided by Aaron Bertrand.
select t.*
from table t
where t.opened >= '2016-08-01' and
t.opened < '2020-05-02'
If your opened is in the same date format, then use:
select t.*
from table t
where convert(date, t.opened, 103) >= '2016-08-01' and
convert(date, t.opened, 103) < '2020-05-02'
However, you should fix your table so the dates are stored using the correct types, not strings.

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 Query: Convert to dd/mm/yyyy from datetime

I'm querying a max datetime to bring in the most recent record from another table surrounding a common ID coloumn. I would like to however format this datetime in the standard UK dd/mm/yyyy format. How would I do so? I just cant seem to get this...
Here is my code:
(SELECT TOP 1 MemberPayments.CoverFinishDay
FROM
Members LEFT JOIN MemberPayments
ON Members.MemberID = MemberPayments.MemberID
AND CoverFinishDay = (
SELECT MAX(CoverFinishDay)
FROM MemberPayments
WHERE Members.MemberID = MemberPayments.MemberID
))
CoverFinishDay is stored in standard american datetime. currently the query works, just in the wrong format. I need the output in dd/mm/yyyy
This will help you:
SELECT CONVERT(VARCHAR, GETDATE(), 105)
This is for SQL Sever
If you are using SQL Server 2012 you can convert any date using FORMAT function. In your case you can do like this:
SELECT FORMAT (MemberPayments.CoverFinishDay, 'd', 'en-GB')
For mor info you can access the page: http://msdn.microsoft.com/en-us/library/hh213505(v=sql.110).aspx

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.