Tôi đã làm thử và thành công, cấu hình máy thử nghiệm:
- Windows Server 2008R2 64 bit
- SQL Server 2008R2 64 bit
Tôi phải cấu hình SQL Server như sau:
sp_configure 'show advanced options', 1 GO RECONFIGURE; GO sp_configure 'Ole Automation Procedures', 1 GO RECONFIGURE; GO sp_configure 'show advanced options', 1 GO RECONFIGURE;
Sau đó tôi phải download và cài đặt file AccessDatabaseEngine_x64.exe tại link sau:
http://www.microsoft.com/en-us/download/details.aspx?id=13255
Tiếp theo, tạo 1 Stored Procedure như đoạn script sau:
create procedure spExecute_ADODB_SQL @DDL varchar(2000), @DataSource Varchar(100), @Worksheet varchar(100)=null, @ConnectionString varchar(255) = 'Provider=Microsoft.ACE.OLEDB.12.0; Data Source=%DataSource; Extended Properties=Excel 12.0' as Declare @objExcel int, @hr int, @command varchar(255), @strErrorMessage varchar(255), @objErrorObject int, @objConnection int, @bucket int Select @ConnectionString =replace (@ConnectionString, '%DataSource', @DataSource) if @Worksheet is not null Select @DDL=replace(@DDL,'%worksheet',@Worksheet) Select @strErrorMessage='Making ADODB connection ', @objErrorObject=null EXEC @hr=sp_OACreate 'ADODB.Connection', @objconnection OUT if @hr=0 Select @strErrorMessage='Assigning ConnectionString property "' + @ConnectionString + '"', @objErrorObject=@objconnection if @hr=0 EXEC @hr=sp_OASetProperty @objconnection, 'ConnectionString', @ConnectionString if @hr=0 Select @strErrorMessage ='Opening Connection to XLS, for file Create or Append' if @hr=0 EXEC @hr=sp_OAMethod @objconnection, 'Open' if @hr=0 Select @strErrorMessage ='Executing DDL "'+@DDL+'"' if @hr=0 EXEC @hr=sp_OAMethod @objconnection, 'Execute', @Bucket out , @DDL if @hr<>0 begin Declare @Source varchar(255), @Description Varchar(255), @Helpfile Varchar(255), @HelpID int EXECUTE sp_OAGetErrorInfo @objErrorObject, @source output, @Description output,@Helpfile output,@HelpID output Select @strErrorMessage='Error whilst ' +coalesce(@strErrorMessage,'doing something')+', ' +coalesce(@Description,'') raiserror (@strErrorMessage,16,1) end EXEC @hr=sp_OADestroy @objconnection go --Bây giờ chạy stored trên để tạo file Excel spExecute_ADODB_SQL @DDL='Create table EmailAddress (EmailAddressID Text, EmailAddress Text)', @DataSource ='C:\EmailAddress.xls' --Tiếp theo tạo 1 linked server kết nối đến file Excel vừa tạo EXEC sp_addlinkedserver 'EmailAddressDatabase', @srvproduct = '', @provider = 'Microsoft.ACE.OLEDB.12.0', @datasrc = 'C:\EmailAddress.xls', @provstr = 'Excel 12.0;' GO EXEC sp_addlinkedsrvlogin 'EmailAddressDatabase', 'false' GO --Bây giờ, insert dữ liệu vào file Excel insert into EmailAddressDatabase...EmailAddress (EmailAddressID, EmailAddress) SELECT EmailAddressID, EmailAddress FROM AdventureWorks2008R2.Person.EmailAddress
Bây giờ, copy file Excel đến 1 máy khác có cài Excel và kiểm tra kết quả
Link tham khảo:
https://www.simple-talk.com/sql/t-sql-programming/sql-server-excel-workbench/
0 comments:
Post a Comment