search
HomeDatabaseMysql Tutorial通过异类查询(OpenDataSource)把外部数据(Excel,TXT)导入到SqlSe

无论用sqlcmd或者通过C#逻辑处理,或者还是直接在SqlServer里执行操作,个人总结大概不过可归总为这两种方式: 1,SSIS; 2,OLEDB驱动引擎。 SSIS实在也好用,现在这里先不去讨论。其中大多数人用的都是第二种方法,下面,本人也以第二种方法在SqlServer里导

无论用sqlcmd或者通过C#逻辑处理,或者还是直接在SqlServer里执行操作,个人总结大概不过可归总为这两种方式:
1,SSIS;
2,OLEDB驱动引擎。


SSIS实在也好用,现在这里先不去讨论。其中大多数人用的都是第二种方法,下面,本人也以第二种方法在SqlServer里导入excel和txt格式文件的具体实例来说明怎样在项目里灵活通过OLEDB导入数据!

一,必要的环境说明

本实例用sql语句在SqlServer里面完成对数据的导入操作。
在本实例开始之前,可能需要先安装AccessDatabase引擎包
(本人机器64位,安装的是32位的office组件,所以需要另外安装office驱动引擎包(此引擎包作用在于使得office系统文件与office应用程序之间进行数据传输) - 此步骤中需要先卸载32位office组件,否则会提示驱动安装不成功)
本人所用引擎包下载地址如下:
http://www.microsoft.com/zh-cn/download/details.aspx?id=13255
安装完成后,具体配置可以这里配,建议如非必要,默认就好。
\

二,代码准备 - 建数据库及存储过程

建数据库这里不多说,建立与导入数据相匹配的数据库而已。
而为了项目拓展及方便使用管理,需要创建存储过程,目的是为了批量导入外部数据。
因为本例以excel和txt分别来做实例说明,所以,需要新建两个存储过程 - "sp_ReadXLSSource"和"sp_ReadSource"。代码分别如下:
存储过程:sp_ReadXLSSource
USE [CUSTOMS]
GO
/****** Object:  StoredProcedure [dbo].[sp_ReadXLSSource]    Script Date: 11/21/2014 3:01:39 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[sp_ReadXLSSource]
@trgPath varchar(255),
@trgTable varchar(255),
@xlsFile varchar(255),
@xlsSheet varchar(255),
@xlsFields varchar(8000)
AS
declare @mySql varchar(8000)
declare @myIntermediate varchar(8000)
declare @Firstfield varchar(100)
declare @FirstfieldValue varchar(100)

--Lookup lastfield
set @Firstfield = dbo.fnGetFirstField(@xlsFields)
set @FirstfieldValue = RTRIM(LTRIM(SUBSTRING(@Firstfield,2,CHARINDEX(']',@Firstfield,0)-2)))
--PRINT @FirstfieldValue

--Drop table if exists
set @myIntermediate = 'IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''[dbo].[' + @trgTable + ']'') AND type in (N''U''))'
set @mySql = @myIntermediate + ' DROP TABLE ' + @trgTable
exec(@mySql)
--PRINT @mySql

--Load Table
set @mySql = 'SELECT ' + @xlsFields + ' INTO ' + @trgTable + ' FROM OPENROWSET(''Microsoft.ACE.OLEDB.12.0'',  
''Excel 12.0;DATABASE=' + @trgPath + '\' + @xlsFile + ';IMEX=1'',  ''Select * from ' + @xlsSheet + ''')'
+ 'WHERE NOT ' + @Firstfield + ' IS NULL'
--PRINT @mySql
exec(@mySql)
存储过程:sp_ReadSource
USE [WOOX_CQM]
GO
/****** Object:  StoredProcedure [dbo].[sp_ReadSource]    Script Date: 11/21/2014 2:54:33 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[sp_ReadSource]
@trgPath varchar(255),
@trgTable varchar(255),
@trgFields varchar(8000)
AS
declare @mySql varchar(8000)
declare @myIntermediate varchar(8000)
declare @Firstfield varchar(100)
declare @FirstfieldValue varchar(100)

--Lookup lastfield
set @Firstfield = dbo.fnGetFirstField(@trgFields)
set @FirstfieldValue = RTRIM(LTRIM(SUBSTRING(@Firstfield,2,CHARINDEX(']',@Firstfield,0)-2)))
--PRINT @FirstfieldValue

--Drop table if exists
set @myIntermediate = 'IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''[dbo].[' + @trgTable + ']'') AND type in (N''U''))'
set @mySql = @myIntermediate + ' DROP TABLE ' + @trgTable
exec(@mySql)
--PRINT @mySql

--Load Table
set @mySql = 'SELECT ' + @trgFields + ' INTO ' + @trgTable + ' ' +
'FROM OpenDataSource (''Microsoft.ACE.OLEDB.12.0'',
''Data Source="' + @trgPath + '";Extended properties=Text'')...' 
+ @trgTable + '#txt ' 
+ &#39;WHERE NOT &#39; + @Firstfield + &#39; IS NULL AND &#39; + @Firstfield + &#39; <> &#39; + &#39;&#39;&#39;&#39; + @FirstfieldValue + &#39;&#39;&#39;&#39;
--PRINT @mySql
exec(@mySql)

三,文件准备,导入源及Schema.ini配置文件

对于excel文件来说,相对txt格式,实在简单很多,关键不过以下这段代码
TRUNCATE TABLE WOOX_INFORMATICA..VBPA;
INSERT INTO WOOX_INFORMATICA..VBPA select * FROM OPENROWSET(&#39;Microsoft.ACE.OLEDB.12.0&#39;, &#39;Excel 12.0;Database=C:\InitialData\db_data.xlsx;HDR=YES&#39;, &#39;SELECT * FROM [VBPA$]&#39;)
--(适用于office2007及以上版本,2003用Jet - "Microsoft.Jet.OLEDB.4.0")
其它需要注意的不过就是保证excel内的数据格式是统一的文本格式,这里只简单给出事例图,不做详细说明。
\

对于txt格式文件,本人所用格式如下。
vcr9vt21xMXk1sPOxLz+U2NoZW1hLmluaaOhyOe5+7W8yOuyu7PJuaa78tXfs/a07aOstPO2vMrH1eLSu7K91ui07cHLPGJyPgqjqHBzo7q0y8Xk1sPOxLz+0qq6zbW8yOvUtLfF1NrNrNK7uPbOxLz+vNDPwqOswe3N4qOszsS8/rzQxL/CvNfuusOx8Myrs6S78tXfsPy6rNPQv9UmIzI2Njg0O9auwOC1xKOs1eLQqdfUvLrXotLio6GjqTxicj4KxuTW0FNjaGVtYS5pbmnA77nmt7YmIzI2Njg0O8q9yOfPwqGjPHByZSBjbGFzcz0="brush:sql;">[SAP_TVSTZ.txt] FORMAT=Delimited(|) ColNameHeader=True MaxScanRows=0 CharacterSet=Unicode TextDelimiter=` Col1=SKIP1 TEXT Col2=SKIP2 TEXT COL3=VSBED TEXT COL4=LADGR char(100) COL5=WERKS TEXT COL6=LGORT TEXT COL7=VSTEL TEXT
\
这里需要标明的是:域值内,第一行表示数据源文件名;第二行至第六行是必要的设置和说明,每个人按需修改;第七行以下必须按照Col从1索引开始递增,右边是显示的列名及格式。具体有兴趣的同学可以自己试着操作下,看下差异。

四,执行及检查

执行代码如下
USE WOOX_CQM

EXECUTE sp_ActivateDistributedQueries
----------------------------- SAP Tables -----------------------------
DECLARE @LoadPath varchar(2000)
SET @LoadPath = &#39;C:\InitialData\SAPdata&#39;

--import Excel--
EXECUTE sp_ReadXLSSource 
@LoadPath, 
&#39;SAP_TCURF&#39;, &#39;SAP_TCURF.xls&#39;, &#39;[Sheet1$]&#39;,
&#39;[KURST],[FCURR],[TCURR],[GDATU], [FFACT],[TFACT],[FromDate],[ToDate]&#39;

--import txt--
EXECUTE sp_ReadSource 
@LoadPath, 
&#39;SAP_TVSTZ&#39;, 
&#39;[VSBED],[LADGR],[WERKS],[LGORT],[VSTEL]&#39;
可用以下代码先行测试导入数据是否有差距,同学们记得更改本人所用的hardcored。
select * 
FROM OpenDataSource (&#39;Microsoft.ACE.OLEDB.12.0&#39;,
&#39;Data Source="C:\InitialData\SAPdata";Extended properties=Text&#39;)...SAP_TW06S#txt
ok,大概代码就是这样,如果有什么不懂或者有不同意见的,可用留言讨论!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to Grant Permissions to New MySQL UsersHow to Grant Permissions to New MySQL UsersMay 09, 2025 am 12:16 AM

TograntpermissionstonewMySQLusers,followthesesteps:1)AccessMySQLasauserwithsufficientprivileges,2)CreateanewuserwiththeCREATEUSERcommand,3)UsetheGRANTcommandtospecifypermissionslikeSELECT,INSERT,UPDATE,orALLPRIVILEGESonspecificdatabasesortables,and4)

How to Add Users in MySQL: A Step-by-Step GuideHow to Add Users in MySQL: A Step-by-Step GuideMay 09, 2025 am 12:14 AM

ToaddusersinMySQLeffectivelyandsecurely,followthesesteps:1)UsetheCREATEUSERstatementtoaddanewuser,specifyingthehostandastrongpassword.2)GrantnecessaryprivilegesusingtheGRANTstatement,adheringtotheprincipleofleastprivilege.3)Implementsecuritymeasuresl

MySQL: Adding a new user with complex permissionsMySQL: Adding a new user with complex permissionsMay 09, 2025 am 12:09 AM

ToaddanewuserwithcomplexpermissionsinMySQL,followthesesteps:1)CreatetheuserwithCREATEUSER'newuser'@'localhost'IDENTIFIEDBY'password';.2)Grantreadaccesstoalltablesin'mydatabase'withGRANTSELECTONmydatabase.TO'newuser'@'localhost';.3)Grantwriteaccessto'

MySQL: String Data Types and CollationsMySQL: String Data Types and CollationsMay 09, 2025 am 12:08 AM

The string data types in MySQL include CHAR, VARCHAR, BINARY, VARBINARY, BLOB, and TEXT. The collations determine the comparison and sorting of strings. 1.CHAR is suitable for fixed-length strings, VARCHAR is suitable for variable-length strings. 2.BINARY and VARBINARY are used for binary data, and BLOB and TEXT are used for large object data. 3. Sorting rules such as utf8mb4_unicode_ci ignores upper and lower case and is suitable for user names; utf8mb4_bin is case sensitive and is suitable for fields that require precise comparison.

MySQL: What length should I use for VARCHARs?MySQL: What length should I use for VARCHARs?May 09, 2025 am 12:06 AM

The best MySQLVARCHAR column length selection should be based on data analysis, consider future growth, evaluate performance impacts, and character set requirements. 1) Analyze the data to determine typical lengths; 2) Reserve future expansion space; 3) Pay attention to the impact of large lengths on performance; 4) Consider the impact of character sets on storage. Through these steps, the efficiency and scalability of the database can be optimized.

MySQL BLOB : are there any limits?MySQL BLOB : are there any limits?May 08, 2025 am 12:22 AM

MySQLBLOBshavelimits:TINYBLOB(255bytes),BLOB(65,535bytes),MEDIUMBLOB(16,777,215bytes),andLONGBLOB(4,294,967,295bytes).TouseBLOBseffectively:1)ConsiderperformanceimpactsandstorelargeBLOBsexternally;2)Managebackupsandreplicationcarefully;3)Usepathsinst

MySQL : What are the best tools to automate users creation?MySQL : What are the best tools to automate users creation?May 08, 2025 am 12:22 AM

The best tools and technologies for automating the creation of users in MySQL include: 1. MySQLWorkbench, suitable for small to medium-sized environments, easy to use but high resource consumption; 2. Ansible, suitable for multi-server environments, simple but steep learning curve; 3. Custom Python scripts, flexible but need to ensure script security; 4. Puppet and Chef, suitable for large-scale environments, complex but scalable. Scale, learning curve and integration needs should be considered when choosing.

MySQL: Can I search inside a blob?MySQL: Can I search inside a blob?May 08, 2025 am 12:20 AM

Yes,youcansearchinsideaBLOBinMySQLusingspecifictechniques.1)ConverttheBLOBtoaUTF-8stringwithCONVERTfunctionandsearchusingLIKE.2)ForcompressedBLOBs,useUNCOMPRESSbeforeconversion.3)Considerperformanceimpactsanddataencoding.4)Forcomplexdata,externalproc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.