Solution for "n" in "SELECT top N *" statement cannot be a variable

Source: Internet
Author: User
Tags prepare stmt
Some time ago, want to write a return to a specified number of records procedure, the code is as follows:

CREATE PROCEDURE Getsomearticles

@cnt int = 1

As

SELECT Top @cnt * from articles

Results found unable to run, always have problems, baffled, and then asked the teacher to know, SELECT top n Here the parameter n can only be a constant, cannot be a variable.

If you define an SQL statement directly in your program and then execute it, you can achieve the desired result:

int cnt = 10;
String strSQL = "SELECT top" + CNT. ToString () + "* from articles";

I wrote it myself. A class of operations databases that apply factory design patterns
A method of encapsulating n multi-operation database
and realize the database independence
That is, you can use the same code to manipulate access, MS SQL SERVER, MySQL
In theory can also achieve the operation of Oracle, but did not use it, so temporarily did not realize, hehe
Commdb db = Createdb.create ();
Performs a database operation, returning a dataset
DataSet ds = db. Execsql (strSQL);
But I do have the need to use stored procedures to achieve, this can do. Fortunately, there is a dynamic execution of SQL (I do not know whether this statement is accurate, for the moment), so we can write the stored procedure:

CREATE PROCEDURE Getsomearticles

@cnt int = 1

As

EXEC ("select top" + @cnt + "* FROM articles")

This solves the problem that n can only be a constant in select top N ^_^

In addition, to achieve similar functionality in MySQL, you can write this:

DELIMITER $$

CREATE PROCEDURE ' Getsomearticles ' (in CNT int)
BEGIN
Set @stmt = concat (' SELECT * from articles LIMIT 0,? ');
Prepare S1 from @stmt;
Set @s1 = CNT;
Execute S1 using @s1;
deallocate prepare S1;
end$$

DELIMITER;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.