Solved

Use a table column as a value in an SQL Query

Posted on 2016-07-26
6
56 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 32

Accepted Solution

by:
Stefan Hoffmann earned 250 total points
Comment Utility
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
Comment Utility
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]
Comment Utility
here is the link, i forgot persisted in the alter table
https://technet.microsoft.com/en-us/library/ms191250(v=sql.105).aspx
1
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 

Author Closing Comment

by:earwig75
Comment Utility
Thank you for the great responses.
0
 
LVL 26

Expert Comment

by:Chris Luttrell
Comment Utility
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 32

Expert Comment

by:Stefan Hoffmann
Comment Utility
@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

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

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 backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
Viewers will learn how the fundamental information of how to create a table.

771 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

15 Experts available now in Live!

Get 1:1 Help Now