?
Solved

Use a table column as a value in an SQL Query

Posted on 2016-07-26
6
Medium Priority
?
68 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
6 Comments
 
LVL 35

Accepted Solution

by:
ste5an earned 1000 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 143

Assisted Solution

by:Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3] earned 1000 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 143

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
Simplifying Server Workload Migrations

This use case outlines the migration challenges that organizations face and how the Acronis AnyData Engine supports physical-to-physical (P2P), physical-to-virtual (P2V), virtual to physical (V2P), and cross-virtual (V2V) migration scenarios to address these challenges.

 

Author Closing Comment

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

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 35

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

Get real performance insights from real users

Key features:
- Total Pages Views and Load times
- Top Pages Viewed and Load Times
- Real Time Site Page Build Performance
- Users’ Browser and Platform Performance
- Geographic User Breakdown
- And more

Question has a verified solution.

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

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
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…
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
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…
Suggested Courses

801 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