Solved

sql - return date

Posted on 2014-10-22
2
418 Views
Last Modified: 2014-10-23
I want below to return the date of a month ago or whatever the @numofmonth is.

declare @Date as datetime
DECLARE @NumOfMonth AS int
set @NumOfMonth = 1
set @Date = (dateadd(dd,-datepart(dd,getdate())+ 1,dateadd(mm,-@NumOfMonth,getdate())))
print @date

This returns Sep  1 2014 11:39AM
0
Comment
Question by:VBdotnet2005
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 65

Assisted Solution

by:Jim Horn
Jim Horn earned 250 total points
ID: 40397903
So how does there year come into play?   Assuming the YEAR(GETDATE()),
DECLARE @NumOfMonth AS int = 1

Declare @dt date = CAST(GETDATE() as date) 

declare @dt_passed_month as date 

SET @dt_passed_month = CAST(CAST(YEAR(@dt) as char(4)) + '-' + RIGHT('0' + CAST(@NumOfMonth as varchar(2)),2) + '-01' as date) 

PRINT DATEADD(m, -1, @dt_passed_month)

Open in new window

0
 
LVL 69

Accepted Solution

by:
Scott Pletcher earned 250 total points
ID: 40397961
Don't mess with strings, they will slow you down and depend on regional settings.  Instead, use straight "date math" ... which is simpler and more consistent anyway once you get used to it :-).


DECLARE @Date as datetime
DECLARE @NumOfMonth AS int

SET @NumOfMonth = 1
SET @Date = DATEADD(MONTH, @NumOfMonth - 1, DATEADD(YEAR, YEAR(GETDATE()) - 1900, 0))

PRINT @date
0

Featured Post

U.S. Department of Agriculture and Acronis Access

With the new era of mobile computing, smartphones and tablets, wireless communications and cloud services, the USDA sought to take advantage of a mobilized workforce and the blurring lines between personal and corporate computing resources.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
In this article we will learn how to fix  “Cannot install SQL Server 2014 Service Pack 2: Unable to install windows installer msi file” error ?
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.

739 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question