mysql - multiple case statements with same logic in when -
i want use case statement each column in mysql. logic inside when of each case statement same long list. there way write optimally. like
case when cond1 'xyz' col1, 'xyz2' col2, 'uuy' col3 else null each column end.
short answer: no
long answer: kind of. can play either wrapping logic function , call each column (if applicable) or play dynamic query - dirty work. consider this:
create table t ( alef varchar(100), bet varchar(100)); set @case := 'case when ''?'' = ''a'' 1 else 0 end'; set @sql := concat('select ',replace(@case,'?','alef'),',',replace(@case,'?','bet'),' t'); prepare stmt @sql; execute stmt;
finally if you're lazy ;) can iterate through information_schema.columns view , dynamically create select statement s.t. along these lines:
set @subcase := ''; select @subcase := concat(@subcase,replace(@case,'?',column_name),',') information_schema.columns table_name = 't';
and these code can safely wrapped in procedure.
Comments
Post a Comment