SQL statement for importing and exporting Excel Data

Source: Internet
Author: User
Importing data from an Excel file to a SQL database is simple.

Importing data from an Excel file to a SQL database is simple.

-- Importing data from an Excel file to a SQL database is simple. Use the following statement:
/* ===================================================== ===================================== */
-- If the table to be imported already exists
Insert into Table select * from
OPENROWSET ('Microsoft. JET. OLEDB.4.0'
, 'Excel 5.0; HDR = YES; DATABASE = c: \ test.xls ', sheet1 $)
-- If you import data and generate a table
Select * into table from
OPENROWSET ('Microsoft. JET. OLEDB.4.0'
, 'Excel 5.0; HDR = YES; DATABASE = c: \ test.xls ', sheet1 $)

/* ===================================================== ===================================== */
-- If you export data from the SQL database to Excel, And the Excel file already exists, and you have created a header based on the data to be received, you can simply use it:
Insert into OPENROWSET ('Microsoft. JET. OLEDB.4.0'
, 'Excel 5.0; HDR = YES; DATABASE = c: \ test.xls ', sheet1 $)
Select * from table

-- If the Excel file does not exist, you can use BCP to import Excel-like files. Note the case sensitivity:
-- Export tables
EXEC master .. xp_mongoshell 'bcp database name. dbo. table name out "c: \ test.xls"/c-/S "server name"/U "username"-P "password "'
-- Export Query Information
EXEC master .. xp_cmdshell 'bcp "SELECT au_fname, au_lname FROM pubs .. authors order by au_lname "queryout" c: \ test.xls "/c-/S" server name "/U" username "-P" password "'
/* -- Description:
C: \ test.xls is the Excel file name for import/export.
Sheet1 $ is the worksheet name of the Excel file. You must add $ to use it normally.
--*/

-- The following is how to export a real Excel file:
If exists (select * from dbo. sysobjects where id = object_id (n' [dbo]. [p_exporttb] ') and OBJECTPROPERTY (id, n' IsProcedure') = 1)
Drop procedure [dbo]. [p_exporttb]
GO
/* -- Data export EXCEL
Export the table data to Excel, including the field name. The file is a real Excel file.
If the file does not exist, the file is automatically created.
If the table does not exist, the table is automatically created.
Only standard data types can be exported for the sake of universality.
-- Producer build 2003.10 (reference please keep this information )--*/
/* -- Call example
P_exporttb @ tbname = 'region information', @ path = 'C: \ ',@fname='aa.xls'
--*/
Create proc p_exporttb
@ Tbname sysname, -- Name of the table to be exported
@ Path nvarchar (1000), -- file storage directory
@ Fname nvarchar (250) = ''-- file name. The default value is table name.
As
Declare @ err int, @ src nvarchar (255), @ desc nvarchar (255), @ out int
Declare @ obj int, @ constr nvarchar (1000), @ SQL varchar (8000), @ fdlist varchar (8000)
-- Parameter detection
If isnull (@ fname, '') = ''set @fname=@tbname='.xls'
-- Check whether the file already exists
If right (@ path, 1) <> '\' set @ path = @ path + '\'
Create table # tb (a bit, B bit, c bit)
Set @ SQL = @ path + @ fname
Insert into # tb exec master .. xp_fileexist @ SQL
-- Database creation statement
Set @ SQL = @ path + @ fname
If exists (select 1 from # tb where a = 1)
Set @ constr = 'driver = {Microsoft Excel DRIVER (*. xls)}; DSN = '''; READONLY = false'
+ '; CREATE_DB = "' + @ SQL + '"; DBQ =' + @ SQL
Else
Set @ constr = 'provider = Microsoft. Jet. OLEDB.4.0; Extended Properties = "Excel 8.0; HDR = YES'
+ '; DATABASE =' + @ SQL + '"'

-- Connect to the database
Exec @ err = sp_oacreate 'ADODB. connection', @ obj out
If @ err <> 0 goto lberr
Exec @ err = sp_oamethod @ obj, 'open', null, @ constr
If @ err <> 0 goto lberr
/* -- If the existing table is overwritten, add the following statement.
-- Delete the table before creating the table./If the table exists
Select @ SQL = 'drop table ['+ @ tbname +']'
Exec @ err = sp_oamethod @ obj, 'execute ', @ out, @ SQL
--*/
-- SQL statement used to create a table
Select @ SQL = '', @ fdlist =''
Select @ fdlist = @ fdlist + ', [' + a. name + ']'
, @ SQL = @ SQL + ', [' + a. name + ']'
+ Case
When B. name like '% char'
Then case when a. length> 255 then 'memo'
Else 'text ('+ cast (a. length as varchar) +') 'end
When B. name like '% int' or B. name = 'bit' then'int'
When B. name like '% datetime' then 'datetime'
When B. name like '% money' then 'money'
When B. name like '% text' then 'memo'
Else B. name end
FROM syscolumns a left join policypes B on a. xtype = B. xusertype
Where B. name not in ('image', 'uniqueidentifier', 'SQL _ variant', 'varbinary', 'binary ', 'timestamp ')
And object_id (@ tbname) = id
Select @ SQL = 'create table ['+ @ tbname
+ '] (' + Substring (@ SQL, 2,8000) + ')'
, @ Fdlist = substring (@ fdlist, 2,8000)
Exec @ err = sp_oamethod @ obj, 'execute ', @ out, @ SQL
If @ err <> 0 goto lberr
Exec @ err = sp_oadestroy @ obj
-- Import data
Set @ SQL = 'openrowset (''microsoft. JET. OLEDB.4.0 '', ''excel 8.0; HDR = YES; IMEX = 1
; DATABASE = '+ @ path + @ fname + ''', [' + @ tbname + '$])'
Exec ('insert into '+ @ SQL +' ('+ @ fdlist +') select' + @ fdlist + 'from' + @ tbname)
Return
Lberr:
Exec sp_oageterrorinfo 0, @ src out, @ desc out
Lbexit:
Select cast (@ err as varbinary (4) as error code
, @ Src as error source, @ desc as error description
Select @ SQL, @ constr, @ fdlist
Go

If exists (select * from dbo. sysobjects where id = object_id (n' [dbo]. [p_exporttb] ') and OBJECTPROPERTY (id, n' IsProcedure') = 1)
Drop procedure [dbo]. [p_exporttb]
GO
/* -- Data export EXCEL
Export the queried data to Excel, including the field name. The file is a real Excel file.
If the file does not exist, the file is automatically created.
If the table does not exist, the table is automatically created.
Only standard data types can be exported for the sake of universality.
-- Producer build 2003.10 (reference please keep this information )--*/
/* -- Call example
P_exporttb @ sqlstr = 'select * from region information'
, @ Path = 'C: \ ',@fname='aa.xls', @ sheetname = 'region information'
--*/
Create proc p_exporttb
@ Sqlstr varchar (8000), -- query statement. If order by is used in the query statement, add top 100 percent.
@ Path nvarchar (1000), -- file storage directory
@ Fname nvarchar (250), -- file name
@ Sheetname varchar (250) = ''-- Name of the worksheet to be created. The default value is the file name.
As
Declare @ err int, @ src nvarchar (255), @ desc nvarchar (255), @ out int
Declare @ obj int, @ constr nvarchar (1000), @ SQL varchar (8000), @ fdlist varchar (8000)
-- Parameter detection
If isnull (@ fname, '') = ''set @fname='temp.xls'
If isnull (@ sheetname, '') ='' set @ sheetname = replace (@ fname ,'.','#')
-- Check whether the file already exists
If right (@ path, 1) <> '\' set @ path = @ path + '\'
Create table # tb (a bit, B bit, c bit)
Set @ SQL = @ path + @ fname
Insert into # tb exec master .. xp_fileexist @ SQL
-- Database creation statement
Set @ SQL = @ path + @ fname
If exists (select 1 from # tb where a = 1)
Set @ constr = 'driver = {Microsoft Excel DRIVER (*. xls)}; DSN = '''; READONLY = false'
+ '; CREATE_DB = "' + @ SQL + '"; DBQ =' + @ SQL
Else
Set @ constr = 'provider = Microsoft. Jet. OLEDB.4.0; Extended Properties = "Excel 8.0; HDR = YES'
+ '; DATABASE =' + @ SQL + '"'
-- Connect to the database
Exec @ err = sp_oacreate 'ADODB. connection', @ obj out
If @ err <> 0 goto lberr
Exec @ err = sp_oamethod @ obj, 'open', null, @ constr
If @ err <> 0 goto lberr
-- SQL statement used to create a table
Declare @ tbname sysname
Set @ tbname = '# tmp _' + convert (varchar (38), newid ())
Set @ SQL = 'select * into ['+ @ tbname +'] from ('+ @ sqlstr +')'
Exec (@ SQL)
Select @ SQL = '', @ fdlist =''
Select @ fdlist = @ fdlist + ', [' + a. name + ']'
, @ SQL = @ SQL + ', [' + a. name + ']'
+ Case
When B. name like '% char'
Then case when a. length> 255 then 'memo'
Else 'text ('+ cast (a. length as varchar) +') 'end
When B. name like '% int' or B. name = 'bit' then'int'
When B. name like '% datetime' then 'datetime'
When B. name like '% money' then 'money'
When B. name like '% text' then 'memo'
Else B. name end
FROM tempdb .. syscolumns a left join tempdb .. policypes B on a. xtype = B. xusertype
Where B. name not in ('image', 'uniqueidentifier', 'SQL _ variant', 'varbinary', 'binary ', 'timestamp ')
And a. id = (select id from tempdb .. sysobjects where name = @ tbname)
If @ rowcount = 0 return
Select @ SQL = 'create table ['+ @ sheetname
+ '] (' + Substring (@ SQL, 2,8000) + ')'
, @ Fdlist = substring (@ fdlist, 2,8000)
Exec @ err = sp_oamethod @ obj, 'execute ', @ out, @ SQL
If @ err <> 0 goto lberr
Exec @ err = sp_oadestroy @ obj
-- Import data
Set @ SQL = 'openrowset (''microsoft. JET. OLEDB.4.0 '', ''excel 8.0; HDR = YES
; DATABASE = '+ @ path + @ fname + ''', [' + @ sheetname + '$])'
Exec ('insert into '+ @ SQL +' ('+ @ fdlist +') select' + @ fdlist + 'from [' + @ tbname + ']')
Set @ SQL = 'drop table ['+ @ tbname +']'
Exec (@ SQL)
Return
Lberr:
Exec sp_oageterrorinfo 0, @ src out, @ desc out
Lbexit:
Select cast (@ err as varbinary (4) as error code
, @ Src as error source, @ desc as error description
Select @ SQL, @ constr, @ fdlist
Go declare @ tbname sysname -- Name of the table to be exported. Note that only the table name/view name can be used.
Declare @ path nvarchar (1000) -- file storage directory
Declare @ fname nvarchar (250) -- file name, default table name
Set @ tbname = 'salaryreport'
Set @ path = 'e :\'
Set @ fname = 'salaryreportsxls'
Declare @ err int, @ src nvarchar (255), @ desc nvarchar (255), @ out int
Declare @ obj int, @ constr nvarchar (1000), @ SQL varchar (8000), @ fdlist varchar (8000)
-- Parameter detection
If isnull (@ fname, '') =''
Set @fname=@tbname='.xls'
-- Drop table # tb
-- Check whether the file already exists
If right (@ path, 1) <> '\' set @ path = @ path + '\'
Create table # tb (a bit, B bit, c bit)
Set @ SQL = @ path + @ fname
Insert into # tb exec master .. xp_fileexist @ SQL
-- Select * from # tb
-- Database creation statement
Set @ SQL = @ path + @ fname
If exists (select 1 from # tb where a = 1)
Set @ constr = 'driver = {Microsoft Excel DRIVER (*. xls)}; DSN = '''; READONLY = false'
+ '; CREATE_DB = "' + @ SQL + '"; DBQ =' + @ SQL
Else
Set @ constr = 'provider = Microsoft. Jet. OLEDB.4.0; Extended Properties = "Excel 5.0; HDR = YES'
+ '; DATABASE =' + @ SQL + '"'
-- Connect to the database
Exec @ err = sp_oacreate 'ADODB. connection', @ obj out
If @ err <> 0 goto lberr
Exec @ err = sp_oamethod @ obj, 'open', null, @ constr
If @ err <> 0 goto lberr
-- SQL statement used to create a table
Select @ SQL = '', @ fdlist =''
Select @ fdlist = @ fdlist + ',' + a. name
, @ SQL = @ SQL + ', [' + a. name + ']'
+ Case when B. name in ('Char ', 'nchar', 'varchar ', 'nvarchar') then
'Text ('+ cast (case when a. length> 255 then 255 else a. length end as varchar) + ')'
When B. name in ('tynyint', 'int', 'bigint', 'tinyint') then 'int'
When B. name in ('smalldatetime', 'datetime') then 'datetime'
When B. name in ('money', 'smallmoney') then 'money'
Else B. name end
FROM syscolumns a left join policypes B on a. xtype = B. xusertype
Where B. name not in ('image', 'text', 'uniqueidentifier', 'SQL _ variant', 'ntext', 'varbinary ', 'binary', 'timestamp ')
And object_id (@ tbname) = id
Select @ SQL = 'create table ['+ @ tbname
+ '] (' + Substring (@ SQL, 2,8000) + ')'
, @ Fdlist = substring (@ fdlist, 2,8000)
Exec @ err = sp_oamethod @ obj, 'execute ', @ out, @ SQL
If @ err <> 0 goto lberr
Exec @ err = sp_oadestroy @ obj
-- Import data
Set @ SQL = 'openrowset (''microsoft. JET. OLEDB.4.0 '', ''excel 5.0; HDR = YES
; DATABASE = '+ @ path + @ fname + ''', [' + @ tbname + '$])'
Exec ('insert into '+ @ SQL +' ('+ @ fdlist +') select' + @ fdlist + 'from' + @ tbname)
Return
Lberr:
Exec sp_oageterrorinfo 0, @ src out, @ desc out
Lbexit:
Select cast (@ err as varbinary (4) as error code
, @ Src as error source, @ desc as error description
Select @ SQL, @ constr, @ fdlist

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.