我尝试创建一个SQL语句为每个添加到数据库的id创建一个.txt
文件,但这不起作用。我试试这个:
DECLARE @FileName varchar(50), @bcpCommand varchar(2000)
SET @FileName = REPLACE('G:\'+CONVERT(char(8),GETDATE(),1)+'.txt','/','-')
SET @bcpCommand = 'bcp "SELECT * FROM dbo.dbTest WHERE (DATEADD(MINUTE,-1420, GETDATE())) < [date];" queryout "'
SET @bcpCommand = @bcpCommand + @FileName + '" -U garth -P pw -c'
PRINT @bcpCommand
当然我需要在G:/中保存这个结果,但这对我不起作用。我的db名称是testDB
答案 0 :(得分:0)
您是不是想要为每个数据库创建一个bcp文件?只需循环遍历所有数据库,并确保为bcp语句指定数据库名称参数,以便它知道执行查询输出查询的数据库。您需要修复的另一件事是文件名。您可以在下面修改它以将数据库名称附加到输出文件,因此您最终不会覆盖每个结果。
DECLARE @FileName varchar(50), @bcpCommand varchar(2000)
declare @x int = 5
declare @y int
declare @dbname varchar(100)
select @y = max(database_id) from sys.databases
while @x <= @y
begin
select @dbname = name from sys.databases where database_id = @x
if @dbname is not null
begin
SET @FileName = REPLACE('G:\'+CONVERT(char(8),GETDATE(),1) +'.txt','/','-')
SET @bcpCommand = 'bcp "SELECT * FROM dbo.dbTest WHERE (DATEADD(MINUTE,-1420, GETDATE())) < [date];" queryout "'
SET @bcpCommand = @bcpCommand + @FileName + '" -U garth -P pw -c -d"' + @dbname + '"'
PRINT @bcpCommand
end
set @x = @x + 1
end
示例结果:
bcp "SELECT * FROM dbo.dbTest WHERE (DATEADD(MINUTE,-1420, GETDATE())) < [date];" queryout "G:\05-16-15.txt" -U garth -P pw -c -d"db1"
bcp "SELECT * FROM dbo.dbTest WHERE (DATEADD(MINUTE,-1420, GETDATE())) < [date];" queryout "G:\05-16-15.txt" -U garth -P pw -c -d"db2"
bcp "SELECT * FROM dbo.dbTest WHERE (DATEADD(MINUTE,-1420, GETDATE())) < [date];" queryout "G:\05-16-15.txt" -U garth -P pw -c -d"db3"
bcp "SELECT * FROM dbo.dbTest WHERE (DATEADD(MINUTE,-1420, GETDATE())) < [date];" queryout "G:\05-16-15.txt" -U garth -P pw -c -d"db4"