Search code examples
mysqlsqlnavicat

Navicat users - any way to create a variable at the top of a New Query and process on the page?


I am essentially trying to create a pHp pdo parameter binding equivalent without the use of php at all.

I use Navicat for my sql queries and building and as such am able to do some more interesting things than say just phpmyadmin.

I have one query in particular which takes a date value and applies it to (literally) 14 if, where, and group by statements. I would like to essentially create a variable at the top of the page, say:

:date

then within the query, apply the variable say:

WHERE date_inserted > :date

I believe this could be done in a stored procedure but I'd like to just keep as a query (within query editor)

edit - example:

In php, you can create a prepared sql query using pdo like the following:

$stmt = $db->prepare("SELECT * FROM tablename WHERE field1 = :field1 AND datefield <= :date1 AND datefield2 >= :date1 AND datefield3 > :date1");

$stmt->bindParam(':field1', $somevariable);
$stmt->bindParam(':date1', $somedate);
$stmt->execute();

I want to do the exact same thing with sql only (using navicat)


Solution

  • This is another answer since you don't want to use join

    SET @@session.var = 'some_value'; 
    select * from table where field = @@session.var
    

    Have not tested but I read from here

    http://forums.mysql.com/read.php?61,127011,127796#msg-127796

    I think the variable will be preserved until the connection is closed and recreated.

    Edit: OP found the rest of the answer. Editing in as requested.

    You can set variables within an SQL call using:

    SET @variablename = [value]
    

    http://dev.mysql.com/doc/refman/5.0/en/user-variables.html