Ask the Expert

Converting SQL Server stored procedures to MySQL dynamic query

I am having a problem during converting a Microsoft SQL Server stored procedure to MySQL in a dynamic query. How can I resolve the dynamic query? Should I query in string? For example: sqlvar=concat('select distinct TOp * from krishna'

    Requires Free Membership to View

The general approach for creating dynamic queries in MySQL stored procedures is correct; construct a string of SQL (using CONCAT as necessary), and then execute that SQL. However, there are a few syntax differences between Microsoft SQL Server and MySQL that come into play.

There is no "TOP" clause in MySQL. Instead, use ORDER BY and LIMIT clauses at the end of the query to return the first few rows from a set:

SELECT * FROM theTable ORDER BY someField LIMIT 5

MySQL offers two types of variables. User variables, prefaced with an '@' symbol, persist beyond the routine. Local variables exist only within the routine. In either case, variable assignments in MySQL stored procedures use the SET or SELECT...INTO statements. Building dynamic queries requires use of a user variable, rather than a local variable, along with the SQL syntax for prepared statements:

SET @statement = CONCAT('SELECT * FROM ', tableNameVariable);
PREPARE myStatement FROM @statement;
EXECUTE myStatement;
Click here for more on stored procedures in MySQL. For more on prepared statements in MySQL, read the manual.

This was first published in August 2006

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: