使用另一个表的列插入mysql表

时间:2017-04-25 05:55:09

标签: mysql sql insert

我想做的事情如下所示

insert into user_audit 
( SELECT COLUMN_NAME
FROM information_schema.columns
WHERE TABLE_NAME='user' and TABLE_SCHEMA = database() )
VAlUES ( SELECT * FROM `user` where id = NEW.id  )

在user_audit中插入用户表的列名和用户表的值

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

您能否请尝试以下动态SQL:

这可能会有所帮助

declare @insertquery nvarchar(1000)
Declare @ColumnNames varchar(2000)
select @ColumnNames = COALESCE(@ColumnNames + ', ', '') + COLUMN_NAME
from 
    INFORMATION_SCHEMA.COLUMNS
where 
    TABLE_NAME='user' and TABLE_SCHEMA = database();

set @insertquery = N'insert into user_audit(' + @ColumnNames + ') SELECT * FROM `user` where id = NEW.id;

sp_executesql @insertquery