Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
Solved

take year from date and convert to a predefined month and date.

Posted on 2013-10-25
Medium Priority
440 Views
is there a better syntax to do the below: a date is given.. it can be any date.. we have to ignore the date and month of that input, but just the year.. then we need the result set of predined April 12th to 16th of that year.

DECLARE @YEAR CHAR(4)
DECLARE @DateBegin CHAR(10)
DECLARE @DateEnd CHAR(10)
select @YEAR = CAST(YEAR('2011-11-19') as CHAR(4)) /*this could be any date */
select @DateBegin = @YEAR+'-04-12'
select @DateEnd = @YEAR+'-04-16'
select  'BETWEEN '''+ @DateBegin+''' AND ''' + @DateEnd +''''

then i have to use the above inside a query in the WHERE condition.
0
Question by:25112
• 2

LVL 15

Expert Comment

ID: 39601140
not sure what you are trying to do there, but if you are going to hardcode it, then hardcode the whole thing
0

LVL 66

Accepted Solution

Jim Horn earned 2000 total points
ID: 39601143
You've pretty much nailed it.  Give this a whirl..
``````Declare @dt date = '2012-05-31'

SELECT CAST(CAST(YEAR(@dt) as char(4)) + '-04-12' as date) as start_date
SELECT CAST(CAST(YEAR(@dt) as char(4)) + '-04-16' as date) as end_date
``````
As an aside, keep in mind that using two dates in BETWEEN means that you're including both of them, and that those two days have a time component of midnight, so it wouldn't capture a value of say 2013-04-16 12:00:00.   SQL expert PortletPaul wrote an article on this.
0

LVL 66

Expert Comment

ID: 39601152
... so, if you want to capture all 2013-04-16 values regardless of time, then instead of

WHERE SomeValue BETWEEN '2013-04-12' AND '2013-04-16'
--  it'll be
WHERE SomeValue >= '2013-04-12' AND SomeValue < '2013-04-17'
0

LVL 5

Author Comment

ID: 39605640
good solution- thx.
0

Featured Post

Question has a verified solution.

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

This post looks at MongoDB and MySQL, and covers high-level MongoDB strengths, weaknesses, features, and uses from the perspective of an SQL user.
MSSQL DB-maintenance also needs implementation of multiple activities. However, unprecedented errors can hamper the database management. In that case, deploying Stellar SQL Database Toolkit ensures fast and accurate database and backup repair as wel…
This video shows how to quickly and easily deploy an email signature for all users in Office 365 and prevent it from being added to replies and forwards. (the resulting signature is applied on the server level in Exchange Online) The email signat…
With just a little bit of  SQL and VBA, many doors open to cool things like synchronize a list box to display data relevant to other information on a form.  If you have never written code or looked at an SQL statement before, no problem! ...  give i…
Suggested Courses
Course of the Month11 days, 18 hours left to enroll