将字符串与查询MySQL混合

时间:2012-10-18 10:56:53

标签: mysql sql join

我正在尝试输出一个字符串以及我从数据库中获得的某些值。例如,在Microsoft Server 2008中,以下方式按我希望的方式运行:

SELECT 
'SELECT c.name COLLATE SQL_Latin1_General_CP1_CI_AS colName, o.name COLLATE SQL_Latin1_General_CP1_CI_AS tableName, '''
+ NAME + ''' db FROM ' + NAME 
+ '.sys.all_columns as c INNER JOIN ' + NAME 
+ 
'.sys.all_objects o ON c.object_id = o.object_id WHERE c.name like ''%password%'' AND type = ''U'' UNION'
  FROM SYS.DATABASES 

返回以下内容:

SELECT c.NAME COLLATE SQL_LATIN1_GENERAL_CP1_CI_AS colName, 
       o.NAME COLLATE SQL_LATIN1_GENERAL_CP1_CI_AS tableName, 
       'master'                                    db 
  FROM MASTER.SYS.ALL_COLUMNS AS c 
       INNER JOIN MASTER.SYS.ALL_OBJECTS o 
               ON c.OBJECT_ID = o.OBJECT_ID 
 WHERE c.NAME LIKE '%password%' 
       AND TYPE = 'U' 
UNION 
SELECT c.NAME COLLATE SQL_LATIN1_GENERAL_CP1_CI_AS colName, 
       o.NAME COLLATE SQL_LATIN1_GENERAL_CP1_CI_AS tableName, 
       'tempdb'                                    db 
  FROM TEMPDB.SYS.ALL_COLUMNS AS c 
       INNER JOIN TEMPDB.SYS.ALL_OBJECTS o 
               ON c.OBJECT_ID = o.OBJECT_ID 
 WHERE c.NAME LIKE '%password%' 
       AND TYPE = 'U' 
UNION 

但是当我在MySQL中尝试类似的事情时:

 SELECT 
'SELECT c.name COLLATE SQL_Latin1_General_CP1_CI_AS colName, o.name COLLATE SQL_Latin1_General_CP1_CI_AS tableName, '''
+ DB + ''' db FROM ' + DB 
+ '.sys.all_columns as c INNER JOIN ' + DB 
+ 
'.sys.all_objects o ON c.object_id = o.object_id WHERE c.name like ''%password%'' AND type = ''U'' UNION'
  FROM DB 

它只返回我想要的记录的空白行。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

在MySQL中,您需要使用concat函数而不是+运算符:

SELECT concat(
'SELECT c.name COLLATE SQL_Latin1_General_CP1_CI_AS colName, o.name COLLATE SQL_Latin1_General_CP1_CI_AS tableName, '''
, DB , ''' db FROM ' , DB 
, '.sys.all_columns as c INNER JOIN ' , DB 
, 
'.sys.all_objects o ON c.object_id = o.object_id WHERE c.name like ''%password%'' AND type = ''U'' UNION'
)  FROM DB