简体   繁体   English

SQL从所有列生成一个字符串

[英]SQL Generating one string from all columns

I'm trying to create a separate log table, made from insert trigger values using now. 我正在尝试创建一个单独的日志表,该表由现在使用插入触发值制成。 The table has a lot of columns, so I was wondering if it is possible to convert all values of the row to one string. 该表有很多列,所以我想知道是否可以将行的所有值转换为一个字符串。

Sample working code with two columns: 有两列的示例工作代码:

CREATE TRIGGER `TEST` AFTER INSERT ON `table` 
FOR EACH ROW BEGIN
    INSERT INTO change_log (string)
       VALUES (CONCAT("User: ", USER(), " Time: ", NOW(), " Insert: " , now.id, now.value));
    END

You can get a list of columns from the catalog. 您可以从目录中获取列列表。 You can (group) concatenate them to form a concatenation expression. 您可以(分组)将它们串联以形成串联表达式。

SELECT concat('concat(',
              group_concat(concat('''',
                                  column_name,
                                  ': '', ',
                                  column_name)
                           SEPARATOR ', '),
              ')')
       FROM information_schema.columns
       WHERE table_schema = '<schema name>'
             AND table_name = '<table name>';

(Replace <schema name> and <table name> with your table's name and its schema.) (用表的名称及其模式替换<schema name><table name> 。)

That will give you an expression like concat('a: ', a, 'b: ', b, 'c: ', c) (if the column name were a , b and c ). 这将为您提供诸如concat('a: ', a, 'b: ', b, 'c: ', c)类的表达式(如果列名分别为abc )。

Amend the result to include your meta data (user, time, etc.) and copy it into your trigger. 修改结果以包括您的元数据(用户,时间等),然后将其复制到触发器中。

Or, if you want, you could also call the query from the catalog in your trigger. 或者,也可以根据需要在触发器中从目录中调用查询。 Amend it, so that in the trigger a string is built which holds the statement you want to execute and execute it with PREPARE ... EXECUTE ... DEALLOCATE PREPARE ... or EXECUTE IMMEDIATE ... (which is essentially shorthand for the former). 对其进行修改,以便在触发器中构建一个包含要执行的语句的字符串,并使用PREPARE ... EXECUTE ... DEALLOCATE PREPARE ...EXECUTE IMMEDIATE ... (它实际上是前任的)。 More information on dynamic SQL in MariaDB can be found in "Prepared Statements " . 有关MariaDB中动态SQL的更多信息,请参见“ Prepared Statements”

使用您的应用程序语言来构建JSON字符串-与您正在执行的操作非常相似,除了它还要处理嵌入式引号和反斜杠。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM