Solved

Limit has variable limits workaround needed?

Posted on 2008-06-20
2
275 Views
Last Modified: 2011-07-08
Seem like I cannot use a variable in a limit clause like so: Limit @rowcount

Is there any workaround for the following syntax?

select @row_count = (Select colRows from tbltemp where colName = 'table1');
set @adj_row_count = (@row_count *.5);

INSERT INTO table2 (col1, col2) Select col1, col2 FROM table1 Limit @adj_row_count

0
Comment
Question by:kvnsdr
2 Comments
 
LVL 9

Accepted Solution

by:
Rurne earned 500 total points
ID: 21833920
You're going to need to create a user function to replicate this.  @variables are not allowed in straightforward SQL in MySQL. See:
http://bugs.mysql.com/bug.php?id=11918
http://bugs.mysql.com/bug.php?id=8094

The alternative is to create a stored procedure and call it instead (e.g., "CALL variable_insert();").  Try:
CREATE PROCEDURE variable_insert()
BEGIN
DECLARE row_count, adj_row_count INT;
SELECT colRows INTO row_count FROM tbltemp WHERE colName = 'table1';
set @adj_row_count = row_count / 2;
 
INSERT INTO table2 (col1, col2) SELECT col1, col2 FROM table1 LIMIT adj_row_count;
END;

Open in new window

0
 
LVL 1

Expert Comment

by:CMDAI
ID: 36151068
Im posting this for people like me who spent ages looking for an easy workaround for limit @variable
# THIS WILL FAIL
select * from some_table limit @a ;

#Instead use this work around
@a=0;
select * from some_table where (@a := @a +1) < @your_limit;

Open in new window

0

Featured Post

Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

Question has a verified solution.

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

Foreword This is an old article.  Instead of using the MySQL extension that was used in the original code examples, please choose one of the currently supported database extensions instead.  More information is available here: MySQLi / PDO (http://…
Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.

685 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