I am trying to create a view on a table called petients in my database. The table has five columns. One of them is the column which I want to keep patient admitted date. It data type is datetime so I want to create a query that filters the data in this table based on current date. For example I want create a view that shows only details of petients who have been recorded on the current day.
Here is my code:
CREATE VIEW [dbo].[recent petients]
AS
SELECT petient_id, name, age, contact
FROM [petients]
WHERE [date] = 'date.Today'
I am getting an error saying that failed to convert date to string. Can you help me to solve it, or where is my code wrong?
Your code looks like SQL Server code. If so, I would recommend:
SELECT petient_id, name, age, contact
FROM [patients]
WHERE [date] = CONVERT(date, GETDATE());
As a note: This version is much better than DATEDIFF() because it allows the use of an index on patient([date]).
If the "date" column has a time component, you can use:
WHERE CONVERT(date, [date]) = CONVERT(date, GETDATE())
Note that this is also index-safe in SQL Server.
I'm assuming you are using Transact-SQL from Microsoft SQL Server, but you should specify the sql dialect you are using.
Since the datetime field type generally includes also a time, it is better to use the DATEDIFF function: https://learn.microsoft.com/it-it/sql/t-sql/functions/datediff-transact-sql?view=sql-server-ver15
In your case, to consider only the record where date=today, the difference in days must be zero:
--SQL QUERY
WHERE DATEDIFF(day, GETDATE(), [date]) = 0
day identifies the element you want to consider the difference. A list of names or abbreviations can be found in the link
GETDATE() returns now datetime
2nd and 3rd arguments are the dates you want to make the difference between
Related
I have a column named CreatedDate of type DateTimeOffset, and I need to query to see rows created today. If this column was of type DateTime I would do this:
SELECT *
FROM MyTable
WHERE CreatedDate >= GETDATE()
How does one accomplish this with a DateTimeOffset column, however?
Environment: SQL Server 2014
Take a look at the TODATETIMEOFFSET function that is built into SQL Server.
Here is an example of how it is used (-5 is my timezone offset...your usage may vary)...again, this also considers you are only worried about >= current time as your original question suggested. You would need to adjust usage of GETDATE() if you care about the entire day (see comment on original question).
select * from TestingDates d where d.CreatedDate >= TODATETIMEOFFSET(GETDATE(), '-05:00')
I am having an issue converting an nvarchar into a date.
The column title is DOS and the dates are formatted like 05-03-2012.
I am trying to convert to a date so I can filter in the where clause.
I have seen explanations using CONVERT(datetime, DOS, 101) but I am not sure where this would go? In the select? In the where clause? Is this the best method to convert varchar into date?
SELECT BedSize
,avg(contributionmargin) AS ContributionMargin
FROM Summary
WHERE DOS > '06-30-2016'
GROUP BY bedsize
HAVING avg(contributionmargin) > 10000
ORDER BY contributionmargin DESC
In this example the where clause is just looking at the '06' in the date and selecting values that are greater than 06, so the results include:
07/01/2013
07/02/2009
08/31/2009
09/25/2012
11/03/2016
12/03/2008
The problem is that the years are ignored.
Option 1:
Add a new datetime column (let's suppose DOSDate) in the table and then run this query
update mytable set DOSDate = STR_TO_DATE(DOS,'%m-%d-%Y')
But future inserts in mytable will also needs to be converted and stored in DOSDate` column.
Option 2:
If you cannot add a new column, use this in where clause
select * from mytable where STR_TO_DATE(DOS,'%m-%d-%Y') > p_mydate
Since you have not provided a query, the above is a sample query to illustrate the point.
UPDATE
Initially you marked your question related to MySQL. For SQL Server you may use CAST or CONVERT instead of STR_To_DATE https://msdn.microsoft.com/en-us/library/ms187928(v=sql.90).aspx
I was able to use the convert function for SQL Server.
This code works:
SELECT BedSize
,avg(contributionmargin) AS ContributionMargin
FROM Summary
WHERE Convert(DATE, DOS, 101) > '06-30-2016'
GROUP BY bedsize
HAVING avg(contributionmargin) > 10000
ORDER BY contributionmargin DESC
I am using the latest SQL Server. I have a table with a CreatedDate column. I need to write a Query that uses dates that are plus or minus 7 from the Date in CreatedDate. I have no clue how to go about this. My thought was this:
DECLARE #Date datetime
DECLARE #SevenBefore datetime
DECLARE #SevenAfter datetime
SET #Date = CreatedDate
SET #SevenBefore = DATEADD(day,-7,#Date)
SET #SevenAfter = DATEADD(day,7,#Date)
SELECT *
FROM <table>
WHERE <table> BETWEEN #SevenBefore AND #SevenAfter
The issue with this is that I cannot use "CreatedDate" as a SET #DATE because SQL gives an error "Invalid column name 'CreatedDate'"
Any help would be appreciated. I cannot list a date because every date in that column could be different.
Thanks
In this case, you need to stop thinking as a programmer would, and start thinking as a Database programmer would.
Lets work only with this central part of your query:
SELECT *
FROM <table>
WHERE <table> BETWEEN #SevenBefore AND #SevenAfter
Now, you say that the CreatedDate is a column in a table. For this example, I will assume that the CreatedDate is in a table other than the one in your example above. For this purpose, I will give two fake names to the tables. The table with the CreatedDate, I will call tblCreated, and the one from the query above I will call tblData.
Looking above, it's pretty obvious that you can't compare an entire table row to a date. There must be a field in that table that contains a date/time value. I will call this column TargetDate.
Given these assumptions, your query would look something like:
SELECT *
FROM tblCreated tc
INNER JOIN tblData td
ON td.TargetDate BETWEEN DATEADD(day, -7, tc.CreatedDate) and DATEADD(day, 7, tc.CreatedDate)
Looking at this, it is clear that you still need some other associations between the tables. Do you only want all data rows per customer based on the Created date, or perhaps only want Creations where some work was done on them as shown in the Data records, or ??. Without a fuller specification, we can't help with that, though.
I have a table which has list of some events with dates. I am trying to write a stored procedure that will return only the upcoming events.
I have written the following query in the stored procedure:
SELECT *
FROM Events
WHERE tDate >= (select CAST(GETDATE() as DATE))
But this is not returning correct result. This is also showing results that have dates less than current date. How to write a query that will return all the events that have date equal or greater than today's date.
Edit: Dates that have been entered on the table have the format yyyy/dd/mm and getdate() returns date in the format yyyy/mm/dd. I think this is causing the problem. Dates that have been entered into the table has been taken using jquery date picker. Any solution to this problem?
Not sure why you have an additional select
SELECT *
FROM Events
WHERE tDate >= CAST(GETDATE() as DATE)
your DATE data is incorrectly stored within Sql Server. When your application passes the string '2015-09-04' and you save that your date column, it is saved as 4th Sept 2015 and not 9th April 2015. Hence your query returns such rows as they are greater than GETDATE().
Example
DECLARE #D VARCHAR(10) = '2015-09-04'
SELECT CONVERT(VARCHAR(20),CONVERT(DATE,#D),109)
you need to fix your data and then use a CONVERT with style when saving dates in your table from application, using something like this. CONVERT(DATE, '20150409',112)
DECLARE #D VARCHAR(10) = '20150409'
SELECT CONVERT(VARCHAR(20),CONVERT(DATE,#D,112),109)
Refer these threads for more info:
Impossible to store certain datetime formats in SQL Server
Cast and Convert
I'm working with SQL Server Reporting Services 2008, which is somewhat new to me, as most of my experience is with LAMP development. In addition, moving most of the logic to SQL as stored procedures is something I'm not very familiar with, but would like to do. Any help or direction would be greatly appreciated.
I need a list of acceptable payroll dates in the form of a table to use as the allowed values for a report parameter. Ideally, the person will be able to select this payroll date from the drop-down provided by the report parameter, which will then be used in the dataset to pull data from a table. I would like the logic to be stored on the SQL server if possible, as this is something that will most likely be used on a few other reports.
The logic to create the list of dates is rather simple. It starts with the oldest payroll date that is need by the system (sometime in 2007) and simply goes every two weeks from there. The procedure or function should return a table that contains all these dates up to and including the nearest upcoming payroll date.
It seems to me that the way to go about this would be a procedure or function that creates a temporary table, adds to it the list of dates, and then returns this table so that the report parameter can read it. Is this an acceptable way to go about it?
Any ideas, examples, or thoughts would be greatly appreciated.
I would use a CTE something like this one:
;WITH PayPeriod AS (
SELECT #DateIn2007 AS p UNION ALL
SELECT DATEADD(dd, 14, p) as P FROM PayPeriod WHERE p < GetDate() )
SELECT p FROM PayPeriod
OPTION ( MAXRECURSION 500 )
The MAXRECURSION and/or where parameter limits the number of dates it will generate.
You can use a parameter to figure out the correct limit to get the correct last date still, of course.
try something like this:
;with AllDates AS
(
SELECT CONVERT(datetime,'1/1/2007') AS DateOf
UNION ALL
SELECT DateOf+14
FROM AllDates
WHERE DateOf<GETDATE()+14
)
SELECT * FROM AllDates
OPTION (MAXRECURSION 500)
you can put this in a view or function.
However, I would suggest that instead of presenting a select box of this many values, why not just have two text box fields: start date and end date and default them to reasonable values, just my 2 cents