Exporting all tables into files from SQL Server database using utility bulk copy

六眼飞鱼酱① 提交于 2019-12-08 04:23:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!