2014-01-24 161 views
0

我想簡化以下使用動態SQL,就像在Transact SQL中可以做的那樣。MySQL變量替換

我想要做的事,如:

SET @s = replace(field_name, '_complete','') 

,並使用@s而不是取代(FIELD_NAME '_complete', '')

請adive如果可能的話,如果是如何。

我當前的代碼:

select distinct  
if(instr(replace(field_name, '_complete',''),'_') <= 5 
      ,left(replace(field_name, '_complete','') 
       ,instr(replace(field_name, '_complete',''),'_') - 1 
      ) 
      ,replace(field_name, '_complete','')  
     ) AS form_id ,replace(
     if(instr(replace(field_name, '_complete',''),'_') <= 5, 
      mid(replace(field_name, '_complete',''), 
       instr(replace(field_name, '_complete',''),'_') + 1, 
       length(replace(field_name, '_complete','')) - instr(replace(field_name, '_complete',''),'_') 
       ) 
      ,replace(field_name, '_complete','') 
     ), 
     '_', 
     ' ') as form_name  ,field_name  from redcap_extract2use where field_name like '%_complete' order by 1; 

以上將被替換爲:

select distinct 
    if(instr(@s,'_') <= 5 ,left(@s,instr(@s,'_') - 1),@s) AS form_id 
    ,replace(if(instr(@s,'_') <= 5, 
     mid(@s,instr(@s,'_') + 1,length(@s) - instr(@s,'_')),@s), '_', ' ') as form_name 
    ,field_name 
    from redcap_extract2use 
    where field_name like '%_complete' 
    order by 1; 

,我也有一個執行...運行查詢

回答

0

如果我米正確理解你的問題,那麼你會想要使用PREPAREEXECUTE陳述。

例如:

SET @s = replace(field_name, '_complete',''); 

PREPARE mystatement FROM 
SELECT DISTINCT ...... ; 

EXECUTE mystatement;