mysql insert语句作为变量

时间:2015-01-09 01:41:11

标签: mysql

是否可以将变量设置为存储过程中的insert语句?

类似的东西:

set variable1 = insert into table(field1, field2, field3) values(val1, val2, variable2);

如果是这样,应该怎么写?

我一直在抛出错误和文档在野外是不确定的。

我的目的是为了简洁,但整个程序是:

-- --------------------------------------------------------------------------------
-- Routine DDL
-- Note: comments before and after the routine body will not be stored by the server
-- --------------------------------------------------------------------------------
DELIMITER $$

CREATE DEFINER=`root`@`localhost` PROCEDURE `new_accession`(in barcode int, in accepted  varchar(11), in wt float(11,2), in wtunit varchar(3),in draw date, in chist varchar(256), in ghist varchar(256), in meds varchar(256), in diffdiag varchar(256),in diseasesus varchar(256),in volume int, in facility int, in patient int, in employ int, in compromised int, in receiving int, in test int)
BEGIN
declare accessionId int;
declare accessionTest int;
declare tkInsert varchar(256);
declare hptInsert varchar(256);
declare calInsert varchar(256);
declare pthInsert varchar(256);
declare vitdtkInsert varchar(256);
declare cnpInsert varchar(256);

if wtunit = 'lb' then set wt = convertLbKg(wt);
end if;

INSERT INTO accession(barcode_accession,accepted_accession,weight_accession,req_weight_units,draw_date_accession,cancer_history_accession,general_history_accession,medication_accession,differential_diagnosis_accession,disease_suspect_accession,volume_accession,facility_doctor_index_id_facility_doctor_index,patient_id_patient,employee_id_employee,accession_compromised_id_accession_compromised,receiving_id,accession_typeof_id_accession_typeof)
VALUES (barcode,accepted,wt,wtunit,draw,chist,ghist,meds,diffdiag,diseasesus,volume,facility,patient,employ,compromised,receiving,1);

set accessionId = last_insert_id();

set tkInsert = insert into pending(accession_facility_index,reagent_type,`status`)values(accessionId,1,'Pending');
set hptInsert = insert into pending(accession_facility_index,reagent_type,`status`)values(accessionId,2,'Pending');
set calInsert = insert into pending(accession_facility_index,reagent_type,`status`)values(accessionId,3,'Pending');
set pthInsert = insert into pending(accession_facility_index,reagent_type,`status`)values(accessionId,4,'Pending');

if test = 1 then tkInsert,calInsert;
elseif test =2 the hptInsert,pthInsert;
else pthInsert;
end if; 


END

2 个答案:

答案 0 :(得分:1)

目前还不是很清楚你想要什么,但如果你的目标是存储insert的结果(受影响的行),你可以使用ROW_COUNT()

  

ROW_COUNT()返回已更改,删除或插入的行数   在最后一个语句中,如果它是UPDATE,DELETE或INSERT。
  对于其他陈述,该值可能没有意义。

例如:

variable1 = (select ROW_COUNT());

答案 1 :(得分:0)

我认为您正在寻找prepared statements

PREPARE tkInsert FROM CONCAT("insert into pending(accession_facility_index,reagent_type,`status`)values(?, 1,'Pending')";

然后用:

执行它
EXECUTE tkInsert USING accessionId;