Solved

Use a table column as a value in an SQL Query

Posted on 2016-07-26
6
61 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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 

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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Why Delete * statement wont work with sql server ? 6 42
optimize stored procedure 6 28
SSAS Hierarchy with columns with folder names 10 14
Increment column based of a FK 8 23
Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

810 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