Convert String column to Date in SSRS - sql

I am trying to write a create statement for creating data source in SSRS. My Create Statement is as follows :-
Select TOP(cast(1000 as integer)) Name,
TName,
IName,
IType,
AvgPercent,
FCount,
PCount,
AvgInPages,
CONVERT(VARCHAR(10),RunDate,103) AS RunDate,
CONVERT(TIME(0), RunTime) AS RTime
from Index
where RunDateBetween #StartDate and #EndDate
Currently I have done it like this CONVERT(VARCHAR(10),RunDate,103) AS RDate, but between clause is not working. Between Clause only gives me record for start date and nothing after that. So I want to convert varchar to date I tried using this after searching on web CONVERT(Date,RunDate,103) AS RunDate but that gives me date as well as time whereas I just need date in that column. After lot of searching I am not able to find any concerete solution.Please help me.

How about this?
SELECT TOP 1000 NAME
,TName
,IName
,IType
,AvgPercent
,FCount
,PCount
,AvgInPages
,CAST(RunDate AS DATE) AS RDate
,CONVERT(TIME(0), RunTime) AS RTime
FROM INDEX
WHERE CAST(RunDate AS DATE) BETWEEN #StartDate
AND #EndDate

Related

incorrect results while passing a datetime instead of getdate()

I am working on a SQL query which returns all records between two dates from a table as follows
select convert(varchar(2),TestDate,108) from dbo.Table
where TestDate between convert(datetime,convert(varchar,GETDATE(),101))
and dateadd(day,1,convert(datetime,convert(varchar,GETDATE(),101)))
The above query works fine and gives me the desired results but when I tried to use a normal date string instead of getdate(), the query returns and empty result as follows
select convert(varchar(2),TestDate,108) from dbo.Table
where TestDate between convert(datetime,convert(varchar,'2015-12-27 00:00:00.000',101)) and dateadd(day,1,convert(datetime,convert(varchar,2015-12-27 00:00:00.000',101)))
The above query returns an empty result set which is not what I wanted.
I tried passing date string in different formats but that didn't work.
May I know a correct way to do it?
Why would you convert dates to a string for comparisons? Just do the comparisons as dates.
In addition, you can use datepart() to extract the hour, rather than using some esoteric format to convert():
select datepart(hour, TestDate)
from dbo.Table
where TestDate between cast(GETDATE() as date) and
cast(dateadd(day, 1, getdate()) as date)
If you want the hour as a string instead of a number, then use datename() rather than datepart().
I guess that you are having an extra CONVERT.
Wherever you have this
convert(varchar,GETDATE(),101)
just replace with your date:
'2015-12-27 00:00:00.000'
because the purpose of the CONVERT function is to translate a Date into a Varchar
In addition to Gordon's answer, you can substitute string dates as so:
select datepart(hour, TestDate)
from dbo.Table
where TestDate between cast('2015-12-27 00:00:00.000' as date) and
cast(dateadd(day, 1, '2015-12-27 00:00:00.000') as date)
Assuming this is for a webapp, be sure to use placeholders instead of actual text to prevent SQL insertion attacks.

TSQL How can I update only the day part of a DATETIME column from a specific day

I would like to run a query on a number of incorrectly time-stamped rows (SQL 2005) and replace the DAY value only. My initial thought was just to use the REPLACE function as follows:
-- date correction
UPDATE mytable
SET [date] = REPLACE([date], '2014-02-20', '2014-02-27')
WHERE [date] LIKE '2014-02-20%'
..but that proved to be unsuccessful most likely because of the given column data-type. Any suggestions ?
You could also just make a DATEADD :
UPDATE mytable
SET [date] = DATEADD(DAY, 7, [date])
WHERE [date] >= '2014-02-20' AND [date] < '2014-02-21'

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.

how to date format 103 to group by using where clause with string format (varchar(103),...,10)

Im having trouble on a query with a datetime field.
Its because i convert the datetime field to -varchar(10),..,103- so i can apply a where clause with date field on 103 format instead of datetime but then when i use the where clause it doesnt show results or group the way i need to, because the datetime field was converted to string.
Here is a simplified query for the example:
select ddate,SUM(ntotal) as Income from Inc_orders
where nbranch=2
and convert(varchar(10),ddate,103)
between '01/06/2010' and '31/06/2010'
group by convert(varchar(10),ddate,103)
order by ddfecha desc
ddate is the datetime field
ntotal is integer
nbranch is foreign key
Then what happens is that i get results from another 103 date range
01/10/2009 4447.0000
02/01/2010 26267.8000
02/02/2010 20498.0000
02/04/2010 22565.1000
02/05/2010 20539.0000
02/11/2010 33934.3000
02/12/2009 33587.4000
What i pretend to look it like is :
01/06/2010 29327.7000
02/06/2010 31170.4000
03/06/2010 37737.7000
04/06/2010 25109.6000
06/06/2010 20819.7000
10/06/2010 44703.9000
14/06/2010 21755.1000
15/06/2010 39369.3000
05/06/2010 29552.2000
07/06/2010 35305.9000
08/06/2010 30628.6000
..........
31/06/2010 18677.6000
A solution is not using datepart, month, or year functions because i need the
parameter to look like a calendar to apply a datetimepicker calentad combo object on it.
Do not use CONVERT(VARCHAR, DateField, 103) to remove the time from DATETIME it is inefficient and also causes problems when sorting.
Depending on the version of SQL-Server you are using there are 2 options that are usually regarded as the best. For SQL-Server 2008 and upwards use CAST(DateField AS DATE), for previous versions use DATEADD(DAY, 0, DATEDIFF(DAY, 0, DateField))
Because you are converting Ddate to a VARCHAR in this line:
convert(varchar(10),ddate,103) between '01/06/2010' and '31/06/2010'
you are removing the implicit conversion of '01/06/2010' and '31/06/2010' to dates. This means '02/01/2000' is greater than '01/01/2012' because you are comparing strings not dates. If you remove the time from Ddate and keep the expression in a date(time) format, '01/06/2010' and '31/06/2010' are implicitly converted to dates.
To illustrate this simply you can run this simple query:
SELECT CASE WHEN '02/06/2000' BETWEEN '01/06/2012' AND '03/06/2012' THEN 1 ELSE 0 END [String Comparison],
CASE WHEN CONVERT(DATETIME, '02/06/2000') BETWEEN '01/06/2012' AND '03/06/2012' THEN 1 ELSE 0 END [Date Comparison]
So your query would end up something like this:
SET DATEFORMAT DMY
SELECT CAST(DDate AS DATE) Ddate,
SUM(ntotal) as Income
FROM Inc_orders
WHERE nbranch=2
AND CAST(DDate AS DATE) BETWEEN '01/06/2010' AND '31/06/2010'
GROUP BY CAST(DDate AS DATE)
ORDER BY DDate
Or
SELECT DATEADD(DAY, 0, DATEDIFF(DAY, 0, DDate)) Ddate,
SUM(ntotal) as Income
FROM Inc_orders
WHERE nbranch=2
AND DATEADD(DAY, 0, DATEDIFF(DAY, 0, DDate)) BETWEEN '01/06/2010' AND '31/06/2010'
GROUP BY DATEADD(DAY, 0, DATEDIFF(DAY, 0, DDate))
ORDER BY DDate
ADDENDUM
I am not sure if Ddate contains a time, so using the above to remove the time may not be relevant, however the part about comparing strings in the where clause remains relevant. In addition there are very few occassions when it should be necessary to present your date to your application in string format. It would be better to keep the date as a date and format it within you application layer (whatever this may be).
Don't convert the date to a string, just leave it as a date:
select ddate,SUM(ntotal) as Income from Inc_orders
where nbranch=2
and ddate between '2010-06-01' and '2010-06-31'
group by nbranch
order by ddate
You can convert ddate in the select list, if you want it to display in a particular way.
You may convert document Date by :
ISNULL(CONVERT(varchar(12),tranInwardHeader.DocumentDate,103),'') AS DocumentDate
Do not use CONVERT nor in GROUP BY, nor in WHERE. use convert on SELECT list of fields
UPDATE:
See valid and recommended formats for DATE CONSTANTS at Microsoft. Please select a any format with "DATEFORMAT dependent: NO" and "Multilanguage: YES" in order to NOT have any problems in any language/setup
UPDATE:
i was writing just the same query #Blorgbeard when I saw: it wont work, because you cant group only by nbranch and have ddate on select list, also nbranch on group by has no sense because, only valid value is 2. You need to redefine your query/needs
I guess, your query may be:
select ddate,SUM(ntotal) as Income from Inc_orders
where nbranch=2
and ddate between '20100601' and '20100631'
group by ddate
order by ddate

To get date from datetime in sql

I have datecreated field in a table. It contains value as "2009-12-30 11:47:20:297"
I have a query like this:
select *
from table
where DateCreated = getdate()
Although one row exists with today's date, I am not getting that row while executing above query. Can anybody help?
The reason why your query doesn't return the row you expect, is because GETDATE() returns the date and time portion at the moment the query was executed. The value in your DateCreated column will not match the time portion, so no rows are returned.
There are various ways to construct a query so that it evaluates the date based on only the date component. Here's one example:
WHERE YEAR(datecreated) = YEAR(GETDATE())
AND MONTH(datecreated) = MONTH(GETDATE())
AND DAY(datecreated) = DAY(GETDATE())
The unfortunate reality is that any query using a function on the column means that if an index exists on the column, it can't be used.
You can use something like this with Sql Server
CREATE FUNCTION [dbo].[udf_DateOnly](#DateTime DATETIME)
RETURNS DATETIME
AS
BEGIN
RETURN DATEADD(dd,0, DATEDIFF(dd,0,#DateTime))
END
This line
DATEADD(dd,0, DATEDIFF(dd,0,#DateTime))
will strip out the Date portion.
The datetime field includes both the date and the time, accurate to the millisecond. Your query will only work if it is the exact millisecond stored in the database.
To check if it is today, but ignore the time of day, you can check for a range like this:
select * from table where
DateCreated >= '2009-12-30' and
DateCreated < '2009-12-31'
You can use that in conjunction with a function that converts the current date, as astander or Khilon has posted. Here is a full example using astander's answer. Also, as Craig Young points out, this will work with indexes.
select * from table where
DateCreated >= DATEDIFF(dd,0,GETDATE()) and
DateCreated < DATEDIFF(dd,0,GETDATE())
The simplest solution might be :
SELECT CAST(GETDATE() as DATE)
You can convert datetime to a string with only the date by using
CONVERT(varchar(8), GETDATE(), 112)
If needed, you can then change it back to datetime and as a result you'll get a datetime with the hours, minutes, seconds and milliseconds set to zero.