Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Declare Date range for multiple SQL queries in series

Posted on 2013-12-12
1
Medium Priority
?
326 Views
Last Modified: 2013-12-23
I have a series of queries where I need to declare a date range, across the multiple queries there are two different fields that will need to use the date range (if that makes any difference).

WHERE CONVERT(DATETIME, DateOfService, 101) BETWEEN '2013-06-01' AND '2013-12-31'

WHERE CONVERT(DATETIME, CHARTED_DATE, 101) BETWEEN '2013-06-01' AND '2013-12-31'

How do I use the declare syntax to describe the between XYZ and ABC range?
0
Comment
Question by:ghettocounselor
1 Comment
 
LVL 25

Accepted Solution

by:
chaau earned 1500 total points
ID: 39715722
Use this syntax:
DECLARE @XYZ DATETIME
DECLARE @ABC DATETIME
SET @XYZ =  '20130601' 
SET @ABC =  '20131231'

' OR use one line assignment like this:
' SELECT @XYZ =  '20130601', @ABC =  '20131231'

WHERE CONVERT(DATETIME, DateOfService, 101) BETWEEN @XYZ AND @ABC

WHERE CONVERT(DATETIME, CHARTED_DATE, 101) BETWEEN @XYZ AND @ABC

Open in new window

BTW, if the DateOfService and CHARTED_DATE are already datetime columns in your database, you do not need CONVERT statement, you can use them directly, like this:
WHERE DateOfService BETWEEN @XYZ AND @ABC

WHERE CHARTED_DATE BETWEEN @XYZ AND @ABC

Open in new window

This way it even be faster, as SQL Server will be able to use indexes
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

As they say in love and is true in SQL: you can sum some Data some of the time, but you can't always aggregate all Data all the time! Introduction: By the end of this Article it is my intention to bring the meaning and value of the above quote to…
PL/SQL can be a very powerful tool for working directly with database tables. Being able to loop will allow you to perform more complex operations, but can be a little tricky to write correctly. This article will provide examples of basic loops alon…
This Micro Tutorial will teach you how to add a cinematic look to any film or video out there. There are very few simple steps that you will follow to do so. This will be demonstrated using Adobe Premiere Pro CS6.
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…

927 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