如何使用变量表示MySQL中的字符串值?下面的存储过程包含两个变量@varname
和@file1
。它还使用concat()
从@file1
创建一个字符串,但这些字符串值都没有正确填充到脚本中。 (查询未加载结果,并且未创建outfile。)如何修复此代码以使其有效?
DELIMITER $$
DROP PROCEDURE IF EXISTS `parse_descriptions`$$
CREATE PROCEDURE `parse_descriptions`()
BEGIN
SET @varname='something';
SET @file1= concat('D:/mypath/','@varname');
select d.id, d.term, d.conceptid from dtablename as d
where term like '%@varname%'
into outfile concat('@file1','_test.txt')
fields terminated by '\t'
optionally enclosed by ""
lines terminated by '\r\n'
;
END$$
CALL `parse_descriptions`()$$
DROP PROCEDURE IF EXISTS `parse_descriptions`$$
答案 0 :(得分:1)
修改了你的代码。认为你在几个地方引用了错误
SET @varname='something';
SET @file1= concat('D:/mypath/',@varname); --here
select d.id, d.term, d.conceptid from dtablename as d
where term like concat('%', @varname, '%') -- here
into outfile concat(@file1,'_test.txt') -- here
fields terminated by '\t'
optionally enclosed by ""
lines terminated by '\r\n'
;
答案 1 :(得分:1)
除了在参数周围的几个地方错放引号之外,因为我已经评论过最大的问题是你试图在select ...into outfile
命令中使用变量,这只能通过prepared statement
完成。下面包含的样本[已测试且工作正常]。您可以根据需要进行相应的更改。
DELIMITER $$
CREATE PROCEDURE `parse_descriptions`()
BEGIN
SET @varname='harikas';
SET @file1= concat('D:/SO_Test/',@varname, '_test.txt');
SET @sql = CONCAT('select * from teachers where username like ''%', @varname, '%'' into outfile ''', @file1 , '''');
select @sql;
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END$$
准备好的语句将生成如下所示的查询
select * from teachers where username like '%harikas%' into outfile
'D:/SO_Test/harikas_test.txt'
调用程序
call parse_descriptions()
编辑:您在该行末尾缺少'
。您修改过的程序应该是
DELIMITER $$
DROP PROCEDURE IF EXISTS `parse_descriptions`$$
CREATE PROCEDURE `parse_descriptions`()
BEGIN
SET @varname='something';
SET @file1= concat('D:/mypath/',@varname, '_test.txt');
SET @sql = concat('select d.id, d.term, d.cid from dtablename as d where term like ''%', @varname, '%'' into outfile ''', @file1 , ''' fields terminated by ''\t'' optionally enclosed by "" lines terminated by ''\r\n''');
select @sql;
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END$$