Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a database table as follows..

PKDrugId - Int
DrugName - Varchar(50)
DrugType - Varchar(25)
CreationDate - Date



I am trying to generate a report which gives all the Drug Names which are entered in the current month. How should i write a query for this in SQL Server 2008?
Posted

SQL
Select * from Drug Where Month(getdate())=Month(CreationDate) and Year(Getdate())=Year(CreationDate)
 
Share this answer
 
v2
Comments
Varun GJ 25-Jan-13 4:05am    
Thank you
Varun GJ 25-Jan-13 4:16am    
How do I Get Previous month for the same scenario?
Devang Vaja 25-Jan-13 4:37am    
Select * from Drug where case Year(getdate) when 12 then Month(getdate())-1=Month(CreationDate) and Year(getdate())-1=year(creationDate) else month(getdate())-1=month(CreationDate) and year(getdate())=year(creationDate) end
You need to use
SQL
DATEPART( datepart , date )


Some useful info on this is available at http://msdn.microsoft.com/en-us/library/ms174420.aspx[^]

I wasn't sure of the table name, so I used tblDrugs.

SQL
SELECT
   DrugName
FROM
   tblDrugs
WHERE
   DATEPART(month,CreationDate) = DATEPART(month, GETDATE())
   AND
   DATEPART(year,CreationDate) = DATEPART(year, GETDATE())


Hope that helps you understand how to use it!

~~~Edit~~~
If you wanted to get last months data you could just subtract 1 from the month.

SQL
SELECT
   DrugName
FROM
   tblDrugs
WHERE
   DATEPART(month,CreationDate) = DATEPART(month,DATEADD(MONTH, -1,GETDATE()) )
   AND
   DATEPART(year,CreationDate) = DATEPART(year, DATEADD(MONTH, -1,GETDATE()))




All the best!
 
Share this answer
 
v4
Comments
Varun GJ 25-Jan-13 4:06am    
Thank You RobBranaghan
Rob Branaghan 25-Jan-13 4:38am    
You're welcome
Varun GJ 25-Jan-13 4:17am    
How do I Get Previous month for the same scenario?
Rob Branaghan 25-Jan-13 4:38am    
See edited code above

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900