如何使用Sql触发器列出表中的所有列

时间:2016-06-17 08:30:14

标签: mysql sql triggers

CREATE TRIGGER `table_triger_on_before_delete`     
BEFORE DELETE ON `db`.`table`     
FOR EACH ROW     
INSERT INTO db_bkp.`table`
    (col1, col2, col3)
VALUES
    (OLD.col1, OLD.col2, OLD.col3)

我想得到这个

(col1, col2, col3)

没有逐个输入

3 个答案:

答案 0 :(得分:1)

可以从MySQL中的information_schema.columns表中查询特定表的列列表。

但是,在这种情况下,您需要使用prepared statement创建插入语句,因为这允许您以字符串形式创建sql命令,然后您可以执行它。

...
declare s_fields, s_sql varchar(1000); --length should depend on how many fields you have
select group_concat(column_name) into s_fields
  from information_schema.columns
  where table_name='yourtable'
  group by table_name
  limit 1;
set s_sql=concat('insert into tablename (',s_fields, ') values (', variable_holding_comma_separated_list_of_values,')');
prepare stmt from s_sql;
execute stmt;
deallocate prepare stmt;
...

答案 1 :(得分:1)

我修改了@Shadow的代码。您还必须包含架构名称。  并且还将它放在反引号中以防止字段名中出现空格。

<ListBox ItemsSource="{Binding Images}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Image Source="{Binding}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

<强>样品

...
DECLARE s_sql VARCHAR(1000); --length should depend ON how many fields you have

SELECT
  CONCAT(
    'insert into tablename ('
    ,GROUP_CONCAT(CONCAT('`',COLUMN_NAME,'`'))
    ,') values ('
    ,GROUP_CONCAT(CONCAT('`OLD`.`',COLUMN_NAME,'`')),
    ')'
  )
  INTO s_sql
FROM information_schema.columns
WHERE
  TABLE_NAME='your_table'
AND
  TABLE_SCHEMA='your_schema'
GROUP BY TABLE_NAME;


prepare stmt from s_sql;
execute stmt;
deallocate prepare stmt;
...

答案 2 :(得分:1)

如果您完全确定表格具有相同的字段,则可以使用

CREATE TRIGGER `table_triger_on_before_delete`     
BEFORE DELETE ON `db`.`table`     
FOR EACH ROW     
INSERT INTO db_bkp.`table`
   SELECT * FROM `db`.`table` WHERE `you_primary_key`=  OLD.`you_primary_key`

因为你的行尚未删除:)