views:

40

answers:

3

In the below SP i will be getting result in One single column. How can i name the column of the output ?

    DELIMITER $$

DROP PROCEDURE IF EXISTS `InsGen` $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `InsGen`
(
in_db varchar(20),
in_table varchar(20),
in_ColumnName varchar(20),
in_ColumnValue varchar(20)
)
BEGIN

declare Whrs varchar(500);
declare Sels varchar(500);
declare Inserts varchar(2000);
declare tablename varchar(20);
declare ColName varchar(20);

set tablename=in_table;


# Comma separated column names - used for Select
select group_concat(concat('concat(\'"\',','ifnull(',column_name,','''')',',\'"\')'))
INTO @Sels from information_schema.columns where table_schema=in_db and table_name=tablename;


# Comma separated column names - used for Group By
select group_concat('`',column_name,'`')
INTO @Whrs from information_schema.columns where table_schema=in_db and table_name=tablename;


#Main Select Statement for fetching comma separated table values
set @Inserts=concat("select concat('insert into ", in_db,".",tablename," values(',concat_ws(',',",@Sels,"),');')
from ", in_db,".",tablename, " where ", in_ColumnName, " = " , in_ColumnValue, " group by ",@Whrs, ";");

PREPARE Inserts FROM @Inserts;

EXECUTE Inserts;

END $$

DELIMITER ;
+1  A: 
SELECT something AS somename ...

In your case, it'd be:

SELECT group_concat(concat('concat(\'"\',','ifnull(',column_name,','''')',',\'"\')')) AS myColumnName
INTO @Sels from information_schema.columns where table_schema=in_db and table_name=tablename;
Charlie Somerville
@Charlie Somerville,It's not working in ur way..I am still gettin this as my column name :"concat('insert into admindb.accounts values(',concat_ws(',',concat('"',ifnull(str_nric,''),'"'),concat('"',ifnull(int_role_type,''),'"'),concat('"',ifnull(str_name,''),'"'),concat('"',ifnull(str_password,''),'"'),concat('"',ifnull(int_login_status,''),'"')"
Anuya
@Charlie Somerville, I think "AS" should be used in this line :PREPARE Inserts FROM @Inserts;EXECUTE Inserts;WHAT DO U THINK ?
Anuya
Have you got the AS statement on both SELECT's?
Charlie Somerville
@ Charlie Somerville, Yeah i added Column name in both the selects.
Anuya
A: 
set @Inserts=concat("select concat('insert into ", in_db,".",tablename," values(',concat_ws(',',",@Sels,"),');') as `Inserts` from ", in_db,".",tablename, " where ", in_ColumnName, " = " , in_ColumnValue, " group by ",@Whrs, ";");

PREPARE Inserts FROM @Inserts;

EXECUTE Inserts;

Add "AS" statement to the first two select statements as advised in the first answer.

ceteras
A: 
This Worked for me : 

set @Inserts=concat("select concat('insert into ", in_db,".",tablename," values(',concat_ws(',',",@Sels,"),');') as MyColumn from ", in_db,".",tablename, " where ", in_ColumnName, " = " , in_ColumnValue, " group by ",@Whrs, ";");
Anuya