MySQL Forums
Forum List  »  Stored Procedures

Re: Dynamic Sql Statement in SP
Posted by: Ming Yeung
Date: January 09, 2006 08:02PM

Thanks for both of your comments, Stefano & Roland.
I have figured out a simple working solution based on your comments.

CREATE PROCEDURE `Search`(IN inUsername VARCHAR(20), IN inRole CHAR, IN inStatus CHAR)
BEGIN

SET @varSqlPrefix = "SELECT * FROM admin";
SET @varSql = '';

IF inUsername IS NOT NULL THEN

IF (@varSql <> '') THEN
SET @varSql = CONCAT(@varSql, ' AND');
END IF;

SET @varSql = CONCAT(@varSql, " username LIKE '%", inUsername, "%'");

END IF;

IF inRole IS NOT NULL THEN

IF (@varSql <> '') THEN
SET @varSql = CONCAT(@varSql, ' AND');

END IF;

SET @varSql = CONCAT(@varSql, " role='", inRole, "'");
END IF;

IF inStatus IS NOT NULL THEN

IF (@varSql <> '') THEN
SET @varSql = CONCAT(@varSql, ' AND');
END IF;

SET @varSql = CONCAT(@varSql, " status='", inStatus, "'");

END IF;

IF (@varSql <> '') THEN
SET @varSql = CONCAT(' WHERE', @varSql);
SET @Sql = CONCAT(@varSqlPrefix, @varSql);
ELSE
SET @Sql = @varSqlPrefix;
END IF;

PREPARE STMT FROM @Sql;
EXECUTE STMT;

END

Env: Java + Mysql
I have found that the input parameters were not null, [a single space]. Then I changed the Java code as:

if(parameter == "") {
cs.setNull(position, java.sql.Types.VARCHAR);
} else {
cs.setString(position, parameter);
}

The setNull() method will set a null value for the IN parameter from Java -> MySql, otherwise, you will get a single space in the SP.

However, the code above is good enough, because code is duplicated. I'm looking for a better way to handle this. E.g. All Stored Procedures {Call} One Single Function to generate dynamic Sql.

Any comments?

Thanks,
Ming

Options: ReplyQuote


Subject
Views
Written By
Posted
2758
January 09, 2006 06:22AM
1481
January 09, 2006 08:06AM
1219
January 09, 2006 02:10PM
Re: Dynamic Sql Statement in SP
1800
January 09, 2006 08:02PM
1685
January 10, 2006 12:24AM
1459
January 10, 2006 03:07AM
1674
January 10, 2006 06:51AM
1397
January 10, 2006 01:49PM
1742
January 10, 2006 06:35PM
1546
January 10, 2006 07:22PM
1631
January 10, 2006 10:33PM
1628
January 11, 2006 03:10AM
2200
January 11, 2006 04:27AM
1656
January 11, 2006 06:54AM
1487
January 11, 2006 03:34PM
1649
January 11, 2006 03:56PM
1637
January 12, 2006 03:20AM
1446
January 12, 2006 04:44AM
1418
January 11, 2006 09:08PM
1666
January 12, 2006 03:11AM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.