views:

216

answers:

3

I have a fairly complex query that will be referencing a single date as a start or stop date multiple times throughout. I'm going to have to run this query for 3 different fiscal years, and don't want to have to hunt down the date 17 times in order to change it throughout my query.

Is there a way to set a variable at the beginning of my query and reference it throughout? I'm not looking to write a whole function, just reference a variable throughout my query.

+2  A: 

Yes, depends how you want to do it.

You could use an anonymous procedure IE:

BEGIN

   v_date DATE := TO_DATE(your_date, your_date_mask);

   [your query referencing v_date where ever you need];

END;

Or if you run the query in SQLPlus, you use & to note variables (IE: &your_date), and will be prompted for the value when you run the script.

OMG Ponies
+1  A: 

As OMG Ponies says, inside PL/SQL you can always refer to any PL/SQL variable (including parameters) right in the SQL as long as it's static SQL. Outside PL/SQL, or if your SQL is dynamic (because native dynamic SQL doesn't support reusable named parameters at least as of 10g) you can use the following trick. Add the following before the WHERE clause in your query:

CROSS JOIN (SELECT :dateparam Mydate FROM dual) Dateview

And everywhere you want to refer to that value in your main query, call it Dateview.Mydate Then when you execute the query, you need only pass in the one bind parameter.

Dan
+1  A: 
David