[英]export inserted table data to .txt file in SQL server
I want to export data of inserted table( temporary table have note of inserted data of the table) to .txt file, I used like this inside trigger我想将插入表的数据(临时表有表插入数据的注释)导出到.txt文件中,我在触发器中是这样使用的
create trigger monitorTrigger on test
for insert
as
declare @sql varchar(8000)
SELECT @sql = 'bcp "select * from inserted" queryout I:\File\mytest.txt -c -t -T -S YAMUNA\SQLEXPRESS'
exec xp_cmdshell @sql
go
this is not working since I didn't give full context(means database.shemaName.tableName) of inserted table.这不起作用,因为我没有提供插入表的完整上下文(意味着 database.shemaName.tableName)。 But the same code is working with normal table since I give full context as但是相同的代码适用于普通表,因为我给出了完整的上下文
declare @sql varchar(8000)
SELECT @sql = 'bcp "select * from test2.dbo.test" queryout I:\File\mytest.txt -c -t -T -S YAMUNA\SQLEXPRESS'
exec xp_cmdshell @sql
I don't know how to query inserted table in bcp
, anyone have any idea?我不知道如何在bcp
查询插入的表,有人知道吗?
You can create another table for temporary storing the results from INSERTED
before calling bcp
.在调用bcp
之前,您可以创建另一个表来临时存储INSERTED
的结果。
create trigger monitorTrigger on test
AFTER insert
as
declare @sql varchar(8000)
--delete it every time
TRUNCATE TABLE test2.dbo.tempInserted
--populate it from inserted
INSERT INTO test2.dbo.tempInserted
SELECT * FROM INSERTED
--use it in bcp
SELECT @sql = 'bcp "select * from test2.dbo.tempInserted" queryout I:\File\mytest.txt -c -t -T -S YAMUNA\SQLEXPRESS'
exec xp_cmdshell @sql
EDIT: Apparently this will not work, because table tempInserted
is locked at the time bcp
is called.编辑:显然这不起作用,因为在调用bcp
表tempInserted
被锁定。
Here is a workaround idea, maybe not the most elegant solution but should work (if you are not on express edition).这是一个解决方法的想法,可能不是最优雅的解决方案,但应该可以工作(如果您不是快速版)。 You can use trigger just to store the inserted data into this table and you can create a job that runs periodically (every 5 mins let's say) and read from that table, copy to file and delete.您可以使用触发器将插入的数据存储到该表中,并且您可以创建一个定期运行的作业(假设每 5 分钟一次)并从该表中读取、复制到文件并删除。
So trigger would be just:所以触发器只是:
create trigger monitorTrigger on test
AFTER insert
as
BEGIN
INSERT INTO test2.dbo.tempInserted
SELECT * FROM INSERTED
END
and Stored Procedure to copy to file - that you can run from the job:和存储过程复制到文件 - 您可以从作业中运行:
CREATE PROC transferToFile
AS
BEGIN
declare @sql varchar(8000)
SELECT @sql = 'bcp "select * from test2.dbo.tempInserted" queryout I:\File\mytest.txt -c -t -T -S YAMUNA\SQLEXPRESS'
exec xp_cmdshell @sql
--delete at the end
TRUNCATE TABLE test2.dbo.tempInserted
END
I worked so我是这样工作的
create trigger monitorTrigger on test
for insert
as
declare @sql varchar(8000)
SELECT @sql = 'bcp "select * from inserted **with (nolock)**" queryout I:\File\mytest.txt -c -t -T -S YAMUNA\SQLEXPRESS'
exec xp_cmdshell @sql
go去
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.