问题
I want to bcp all tables into files from a database:
SELECT 'EXEC xp_cmdshell ''bcp ' --bcp
+ QUOTENAME(DB_NAME())+ '.' --database name
+ QUOTENAME(SCHEMA_NAME(SCHEMA_ID))+ '.' -- schema
+ QUOTENAME(name) -- table
+ ' out c:\temp\' -- output directory
+ REPLACE(SCHEMA_NAME(schema_id),' ','') + '_'
+ REPLACE(name,' ','') -- file name
+ '.txt -T -c''' -- extension, security
FROM sys.tables
it produces statements like this:
EXEC xp_cmdshell 'bcp [AdventureWorks2012].[Production].[ScrapReason] out c:\temp\Production_ScrapReason.txt -T -c'
EXEC xp_cmdshell 'bcp [AdventureWorks2012].[HumanResources].[Shift] out c:\temp\HumanResources_Shift.txt -T -c'
so what I want is to iterate over above statements and execute all them. How to do this?
回答1:
Note this assumes all commands are unique.
DECLARE @Commands TABLE(CommandText NVARCHAR(4000));
DECLARE @SQL NVARCHAR(4000);
INSERT INTO @Commands
SELECT 'EXEC xp_cmdshell ''bcp ' --bcp
+ QUOTENAME(DB_NAME())+ '.' --database name
+ QUOTENAME(SCHEMA_NAME(SCHEMA_ID))+ '.' -- schema
+ QUOTENAME(name) -- table
+ ' out c:\temp\' -- output directory
+ REPLACE(SCHEMA_NAME(schema_id),' ','') + '_'
+ REPLACE(name,' ','') -- file name
+ '.txt -T -c''' -- extension, security
FROM sys.tables
WHILE (SELECT COUNT(*) FROM @Commands) > 0
BEGIN --Command Processing
SET @SQL = (SELECT TOP 1 CommandText FROM @Commands)
--PRINT (@SQL)
EXEC (@SQL)
DELETE FROM @Commands WHERE CommandText = @SQL
END
来源:https://stackoverflow.com/questions/19934411/exporting-all-tables-into-files-from-sql-server-database-using-utility-bulk-copy