1. 程式人生 > >BCP SQL匯出EXCEL常見問題及解決方法;資料匯出儲存過程

BCP SQL匯出EXCEL常見問題及解決方法;資料匯出儲存過程

一、‘xp_cmdshell’的啟用

SQL Server阻止了對元件‘xp_cmdshell’的過程‘sys.xp_cmdshell’的訪問。因為此元件已作為此服務囂安全配置的一部分而被關 閉。系統管理員可以通過使用sp_configure啟用‘xp_cmdshell’。有關啟用‘xp_cmdshell’的詳細資訊

解決方法:

1、通過SQL語句開啟。[推薦此方法,因為在任何版本的SQL SERVER中都可以使用。]
通過查詢分析器,選擇Master資料庫,然後執行以下SQL內容:
sp_configure 'show advanced options',1
reconfigure
go
sp_configure 'xp_cmdshell',1
reconfigure
go

2、開始 --> SQL安裝目錄 --> 配置 SQL server managerment 外圍應用配置器-->“功能的外圍應用配置器”-->找到“xp_cmdshell”點選啟用

 

二、SQLState = S0002, NativeError = 208   Error = [Microsoft][SQL Server Native Client 10.0][SQL Server]物件名 'XXX' 無效。

SQLState = 37000, NativeError = 8180

Error = [Microsoft][SQL Server Native Client 10.0][SQL Server]無法預定義語句。

解決方法: 資料表名補全 [庫名].[使用者名稱].[表名]

 exec  xp_cmdshell 'bcp " select  * from [庫名].[使用者名稱].[表名]" queryout "  路徑 "  -T  -c -U   -P  '

 

三、SQLState = S1000, NativeError = 0

Error = [Microsoft][SQL Server Native Client 10.0]無法開啟 BCP 主資料檔案

解決方法:檢查儲存檔案路徑是否正正確,磁碟是否存在

 

整體解決方法 儲存過程

CARATE  PROCEDURE execname @filename nvarchar(4000),@path nvarchar(2000) 
AS
BEGIN
declare @sql nvarchar(4000)
set @path=Replace (@path,'\','/');  --替換路徑符號
set @filename=Replace (@filename,'from ','from [庫名].[使用者名稱].'); --新增資料表全名
set @sql='bcp "'+@filename+'" queryout "'+@path+'"  -T  -c -U使用者名稱 -P密碼' 
 exec  xp_cmdshell @sql
END