Click here to Skip to main content
15,895,142 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
this query count all record store in database ..i need to get only record of current month ...

What I have tried:

<pre>select  count(*) as present from attendance  where present='P'   and name='dummmy' and [date]>= convert(varchar(11),(DATEADD(mm, DATEDIFF(mm, 0, GETDATE()), 0)),105) and   [date] <=  convert(varchar(11), getdate(), 105)
Posted
Updated 11-Jan-18 21:35pm

The question is what server you are using?
There is a month function in SQL Server 2015 and later:

<pre lang="SQL">Select Month(getdate())


Most likely this should solve your problem.
 
Share this answer
 
Comments
ADI@345 12-Jan-18 2:03am    
I am using sql server 2008..
My question is to show record of first to last date of current month in sql
OK, in that case try the datepart() function extracting the month portion from a datetime:
DATEPART(month, getdate())


DATEPART (Transact-SQL) | Microsoft Docs[^]
 
Share this answer
 
you may try this:

And make sure you add year as well. else if you have records for 3 years in table it might end up providing you count for last 3 years for the provided month.

select  count(*) as present from attendance  where present='P'   and name='dummmy' and
 DATEPART(mm, [date]) = DATEPART(mm, getdate())
AND DATEPART(yy, [date]) = DATEPART(yy, getdate())
 
Share this answer
 
You can't use EOMONTH and DATETIMEFROMPARTS since they arrived with SQL Server 2012, but MONTH and YEAR came with SQL SERVER 2008.
So this should work:
SQL
select  count(*) as present
from    attendance
where   present='P'
    and name='dummmy'
    AND MONTH([date]) = MONTH(SYSDATETIME)
    AND YEAR([date]) = YEAR(SYSDATETIME)
which will perform poorly since it cannot use any indexes on date.
But you wouldn't have been able to use that anyway since from your example it also seems you have stored the date as a varchar in italian format.
So to fix that error we need to add a conversion:
SQL
select  count(*) as present
from    attendance
where   present='P'
    and name='dummmy'
    AND MONTH(CONVERT(DATE,[date],105)) = MONTH(SYSDATETIME)
    AND YEAR (CONVERT(DATE,[date],105)) = YEAR(SYSDATETIME)
 
Share this answer
 
As you are using sql server 2008 , here i create query with help of sql function month(),year()and getdate() ,

Try this query

SELECT  COUNT(*) as present from attendance
WHERE  present='P'and name='dummmy' and MONTH([date]) = MONTH(GETDATE()) and
YEAR([date]) = YEAR(GETDATE())
 
Share this answer
 
v3

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