0

Hi I would really appreciate some help. I would like to declare 2 variables as dates in the date format as date1 = 31-AUG-15 and date2 = 01-SEP-15 and use that within the SELECT statement so I don't need to keep typing in dates everywhere when I need to change the date. Is this possible?

SELECT TABLE1.TRANSACTION_ID, TABLE1.AMOUNT, TABLE1.MATURITY, TABLE1.TYPE,
TABLE1.EFFECTIVE_DATE, TABLE1.SETTLEMENT_DATE, TABLE2.TRANSACTION_DATE 
FROM TABLE1 
LEFT JOIN TABLE2 ON TABLE1.TRANSACTION_ID = TABLE2.TRANSACTION_ID AND TABLE2.TRANSACTION_DATE = date2
WHERE TABLE1.MATURITY > date1
AND TABLE1.EFFECTIVE_DATE > date1
AND TABLE1.SETTLEMENT_DATE = date1
3
  • What RDBMS are you using? Commented Sep 8, 2015 at 16:17
  • You can use a .sql file to contain both the variable declaration and the sql to help reduce repetition, but I am not aware of anything that would let you define a variable, may be you can use the DUAL table on Oracle. Commented Sep 8, 2015 at 16:19
  • I'm just using toad to pull data from an oracle sql database table. I would really appreciate any help Commented Sep 8, 2015 at 16:20

2 Answers 2

0

According to the documentation for Oracle, you should use a DECLARE statement.

This answer will provide more details on dates in particular:

DECLARE 
    date1 DATE := to_date('03/11/2011', 'dd/mm/yyyy');
Sign up to request clarification or add additional context in comments.

Comments

0

You did not specify what type of SQL you are using (MSSQL, MySQL, Oracle SQL, ...). I can help you with a snippet for Microsoft SQL Server.

DECLARE @date1  DATETIME,
        @date2  DATETIME

SET @date1 := '08-31-15'
SET @date2 := '09-01-15'

SELECT TABLE1.TRANSACTION_ID, TABLE1.AMOUNT, TABLE1.MATURITY,
       TABLE1.TYPE, TABLE1.EFFECTIVE_DATE, TABLE1.SETTLEMENT_DATE, TABLE2.TRANSACTION_DATE 
FROM TABLE1 
LEFT JOIN TABLE2 ON TABLE1.TRANSACTION_ID = TABLE2.TRANSACTION_ID AND TABLE2.TRANSACTION_DATE = date2
WHERE TABLE1.MATURITY > date1
      AND TABLE1.EFFECTIVE_DATE > date1
      AND TABLE1.SETTLEMENT_DATE = date1

I hope this helps. I used answers to this question: SQL How to correctly set a date variable value and use it? as a reference.

1 Comment

Thanks Elvar. The table is in Oracle SQL and I am using toad to query. However, I am getting an error encountered the symbol date2 when expecting following :=,(@%; not null range default character

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.