預設關閉,兩種方式開啟:
EXEC sp_configure 'show advanced options', 1; RECONFIGURE;
EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE;

EXEC xp_cmdshell 'bcp "SELECT * FROM sysfiles" queryout "C:\bcptest.txt" -T -c -t,';

| 參數 | 用途 |
|---|---|
queryout | 指定查詢輸出(可用複雜查詢或 View) |
"C:\bcptest.txt" | 輸出檔案完整路徑 |
-T | 信任連線 (Windows 整合驗證);或用 -U user -P pwd |
-c | 字元資料類型 (預設 tab 分隔、換行結束) |
-t, | 欄位分隔符設為逗號 (預設 tab) |
-S Server\Instance | 指定遠端實例 (本機可省略) |
EXEC xp_cmdshell 'bcp "SELECT name, type_desc, create_date FROM sys.objects"
queryout "C:\bcptest2.txt" -T -S DEVELOP\DEV1 -c -t,';
xp_cmdshell 需 sysadmin 權限,生產環境謹慎開啟,用畢即關;-w 參數搭配 nvarchar;