Share via

How to add month and date to get data automatically in SQL?

Pelican 20 Reputation points
2025-03-19T23:40:33.17+00:00

Hello,

I'm new to SQL. I would like to setup below codes in SSMS to automictically run once a month without changing date, month and year? How would I do it? Can I turn into a Stored procedure?

select

T.INVDTE as 'Invoice Date',

T.INVNO as 'Invoice Number',

T.SSTATE as 'State',

LEFT(T.SZIP,5) as 'Zip Code',

RIGHT(T.SZIP,4) as 'Plus 4',

T.SCITY as 'City',

T.COUNTY as 'County',

T.ORIGIN as 'Sold From',

REPLACE(L.ZIP, '-', '') as 'Sold From Zip Code',

L.CITY as 'Sold from City',

T.EXEMPT as ' Excempt Amt',

T.TAXABLE as 'Taxable',

T.NONTXABLE as 'Non-Taxable',

T.EXEMPT + T.NONTXABLE as 'Total of Exempt and Non-Taxable',

1 as 'T',

'N' as 'X',

'N' as 'Y',

T.TAX as 'Tax Collected'

from tblST T

INNER JOIN tblIC L ON T.LOCTID=L.LOCTID

where INVDTE BETWEEN '2022-07-01' and '2022-07-31'

order by STATE

Thank you for guidance

SQL Server | SQL Server Transact-SQL
0 comments No comments

Answer accepted by question author

LiHongMSFT-4306 31,621 Reputation points
2025-03-20T01:45:31.6966667+00:00

Hi @Pelican

Yes, you could wrap your code into a stored procedure and then create a SQL Server Agent job that executes this stored procedure on a monthly schedule.

Considering that there is a date filter in the where condition, you might need to modify it. Cause you did not clarify the detailed logic, so here is the code depending on my guess that you execute this code on the first day of each month to query data from the previous month.

CREATE PROCEDURE [dbo].[MonthlyAutoTask]
AS
BEGIN
    select
	......
	from tblST T INNER JOIN tblIC L ON T.LOCTID=L.LOCTID
	where INVDTE BETWEEN DATEADD(DAY, 1, EOMONTH(GETDATE(), -2)) and EOMONTH(GETDATE(), -1)
	order by STATE
END

Then you could create a SQL Server agent job to run this SP.

You may refer to this guide: Create A SQL Job to Run a Stored Procedure.

Best regards,

Cosmog


If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

Was this answer helpful?

0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.