Created
July 21, 2011 15:07
-
-
Save guohai/1097396 to your computer and use it in GitHub Desktop.
Insert data(string or null, date etc...) with ps, building dynamic sql, excuting with prepare sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| CREATE TABLE `str_test` ( | |
| `id` int(11) NOT NULL AUTO_INCREMENT, | |
| `name` varchar(50) DEFAULT NULL, | |
| `ats` text, | |
| `dor` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, | |
| PRIMARY KEY (`id`) | |
| ) ENGINE=InnoDB DEFAULT CHARSET=utf8 | |
| delimiter $$ | |
| DROP FUNCTION str_filter $$ | |
| CREATE FUNCTION str_filter(in_src TEXT) | |
| RETURNS TEXT DETERMINISTIC | |
| BEGIN | |
| IF in_src IS NOT NULL THEN | |
| RETURN CONCAT('''', in_src, ''''); | |
| ELSE | |
| RETURN 'NULL'; | |
| END IF; | |
| END $$ | |
| CALL test_insert_data_null('guohai','text long long', '2011-07-11 13:33:21', @last_id, @no, @msg) $$ | |
| SELECT @last_id, @no, @msg $$ | |
| DROP PROCEDURE IF EXISTS test_insert_data_null $$ | |
| CREATE PROCEDURE test_insert_data_null(in_name VARCHAR(20), in_ats TEXT, in_dor VARCHAR(20), OUT last_id BIGINT, OUT no INT, OUT msg VARCHAR(50)) | |
| BEGIN | |
| DECLARE INSERT_SQL VARCHAR(200); | |
| SET @MYQUERY := CONCAT('INSERT INTO str_test(name, ats, dor) VALUES(', str_filter(in_name), ',', str_filter(in_ats), ',', 'str_to_date(''', in_dor, ''',', '''%Y-%m-%d %H:%i:%s''))'); | |
| PREPARE INSERT_SQL FROM @MYQUERY; | |
| EXECUTE INSERT_SQL; | |
| DEALLOCATE PREPARE INSERT_SQL; | |
| SELECT LAST_INSERT_ID() INTO last_id; | |
| END $$ | |
| -- of course the efficiency of the method is unsatisfied, but some sometimes we really really hava to do this |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment