Click here to Skip to main content
15,891,938 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,



I have to write a query for generating report that gives sales data of my company. The report have to taken daily in such a way that it should contain data from 1st of the month till the previous day. For eg: report generated on Feb 24 should contain data from 1st Feb to 23 Feb. If the report is generated on 1st of every month, it should contain data for the previous month.

Can anyone help in writing dynamically the WHERE clause in SQL SERVER which satifies both the conditions.

Thanks in advance,

Shanif
Posted

1 solution

All you need to do is to write stored procedure[^] (SP):
SQL
CREATE PROCEDURE GetDataToReport

AS
BEGIN
    --declare varables:
    DECLARE @fdate DATETIME
    DECLARE @pdate DATETIME 
   
    --get current date
    SET @pdate = GETDATE()

    --get first day of month
    SET @fdate = DATEADD(month, DATEDIFF(month, 0, @pdate), 0)

    --get current date - 1
    SET @pdate = DATEADD(dd, -1, @pdate)

    --get data
    SELECT *
    FROM TableName
    WHERE DateField BETWEEN @fdate AND @pdate

END



For further information, please see:
Date and Time Data Types and Functions (Transact-SQL)[^]
Return Data from a Stored Procedure[^]
 
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