Solved

Use a table column as a value in an SQL Query

Posted on 2016-07-26
6
59 Views
Last Modified: 2016-07-26
My Query has a date field, and an integer field. I want to write a query so that if a record has a date older than the number of days specified in the integer field, it will be returned in the query. The integer field is the number of days going back from the current date. For example. If I have 2 records, one with a date of 7/24/2016 and one with a date of 7/21/2016, I only want the record from the 21st to be returned if the integer column is set to 4, since today is less than 4 days since the 24th, but the 21st is older than 4 days ago from today. Can someone assist?

select * from myTable
WHERE DATEDIFF(day,getdate(),myDateColumn) > myIntegerColumn
0
Comment
Question by:earwig75
6 Comments
 
LVL 33

Accepted Solution

by:
ste5an earned 250 total points
ID: 41729581
Posting a concise and complete sample would help..

but you've mixed the start and end date in the DATEDIFF:

DECLARE @myTable TABLE
    (
      ID INT IDENTITY ,
      myDateColumn DATE ,
      myIntegerColumn INT
    );

INSERT  INTO @myTable
        ( myDateColumn, myIntegerColumn )
VALUES  ( '20160724', 4 ),
        ( '20160721', 4 );

SELECT  * ,
        DATEDIFF(DAY, GETDATE(), myDateColumn) ,
        DATEDIFF(DAY, myDateColumn, GETDATE())
FROM    @myTable;

SELECT  *
FROM    @myTable
WHERE   DATEDIFF(DAY, myDateColumn, GETDATE()) > myIntegerColumn; 

Open in new window

0
 
LVL 142

Assisted Solution

by:Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3] earned 250 total points
ID: 41729609
for perfoance reasons, i would avoid to write like that, as a index on the date column could not be used
i would suggest to create a computed column in the table directly, index it...

alter table myTable add your_computed_date = dateadd(day, myDateColumn,myIntegerColumn)

and the query becomes simply and fast

select *
from myTable 
WHERE your_computed_date < getdate()
1
 
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 41729615
here is the link, i forgot persisted in the alter table
https://technet.microsoft.com/en-us/library/ms191250(v=sql.105).aspx
1
Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

 

Author Closing Comment

by:earwig75
ID: 41729656
Thank you for the great responses.
0
 
LVL 26

Expert Comment

by:Chris Luttrell
ID: 41729672
I agree with Guy and like that answer for a solution that performs well as long as you can make those changes to your schema.
In case you can't then you can accomplish not using a function on your column and defeating any indexes on it by writing your query in this manner instead
SELECT * from @myTable mT
WHERE DATEADD(DAY, -mT.myIntegerColumn,getdate()) > mT.myDateColumn

Open in new window

0
 
LVL 33

Expert Comment

by:ste5an
ID: 41729788
@Chris: Any DATEADD() solution will use the same plan, when an index exists:

USE tempdb;
GO

CREATE TABLE myTable 
    (
      ID INT IDENTITY NOT NULL PRIMARY KEY,
      myDateColumn DATE NOT NULL,
      myIntegerColumn INT NOT NULL
    );

CREATE INDEX IX_Date_1 ON myTable ( myDateColumn, myIntegerColumn );
CREATE INDEX IX_Date_2 ON myTable ( myDateColumn ) INCLUDE ( myIntegerColumn );

CREATE INDEX IX_Int_1 ON myTable ( myIntegerColumn, myDateColumn);
CREATE INDEX IX_Int_2 ON myTable ( myIntegerColumn ) INCLUDE ( myDateColumn );
GO

INSERT  INTO myTable
        ( myDateColumn, myIntegerColumn )
VALUES  ( '20160724', 4 ),
        ( '20160721', 4 );
GO

SELECT  *
FROM    myTable
WHERE   DATEDIFF(DAY, myDateColumn, GETDATE()) > myIntegerColumn; 

SELECT  *
FROM    myTable
WHERE DATEADD(DAY, -myIntegerColumn, GETDATE()) > myDateColumn;
GO

DROP TABLE myTable;
GO

Open in new window


Capture.PNG
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

In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

863 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

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now