1

Using views with variables in MySQL

Posted June 18th, 2007 in Databases by Olexandr Melnyk

One of MySQL’s restriction when using views is that they cannot refer to local variables. So, for example, this statement will produce an error:

create view thematical_books as
select title
     , author
  from books
 where subject = @book_subject

A workaround for this limitation is quite simple: to use a function which returns variable value. For example:

create function book_subject()
returns varchar(64) as
return @book_subject;
create view thematical_books as
select title
     , author
  from books
 where subject = book_subject()
Share and Enjoy:
  • Facebook
  • VKontakte
  • MySpace
  • LinkedIn
  • Twitter
  • Identi.ca
  • Tumblr
  • Digg
  • Reddit
  • del.icio.us
  • StumbleUpon
  • Google Bookmarks
  • Google Buzz
  • Live
  • Technorati
  • HackerNews
  • Slashdot
  • Hyves
  • Tuenti
  • PDF
  • Ketil

    I get an error when running your code on MySQL 5.0.51

    #1064 – You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘varchar(64) as
    return @book_subject’ at line 2

blog comments powered by Disqus