Solved

Why is the T-SQL "DATEPART" Not Working?

Posted on 2016-07-26
2
43 Views
Last Modified: 2016-07-26
Hello:

I'm running a simple select statement against a SQL Server 2008 R2 database, as follows:

select * from RM20101 where RMDTYPAL = 7 and DATEPART(y, RM20101.DOCDATE) < '2011'

Open in new window


The RM20101 table is a list of accounts receivable (i.e. "sales") documents.  The syntax " where RMDTYPAL = 7" means to only return a list of credit memos.  Finally, the "DATEPART" syntax is to return credit memos only where the year portion of the document's date is older than the year 2011.

But, if you look at the image that I have embedded, this statement is returning documents dated with the year 2013.

What am I doing wrong?

DOCDATE
Thank you!

John
0
Comment
Question by:John Ellis
2 Comments
 
LVL 70

Accepted Solution

by:
Éric Moreau earned 500 total points
ID: 41730410
because y is dayofyear. you need to use yy or yyyy as shown in https://msdn.microsoft.com/en-us/library/ms174420.aspx
0
 
LVL 48

Expert Comment

by:PortletPaul
ID: 41730451
I have no idea how many rows you have in that table, but for every row you are running a function
e.g. 100,000 rows = 100,000 function executions

Or, you could do this instead which leads to zero function executions

and RM20101.DOCDATE < '20110101' -- i.e. less than Jan 1 2011


"avoid using functions on data in the where clause"
0

Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

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

If you find yourself in this situation “I have used SELECT DISTINCT but I’m getting duplicates” then I'm sorry to say you are using the wrong SQL technique as it only does one thing which is: produces whole rows that are unique. If the results you a…
In this article I will describe the Backup & Restore method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

809 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