Importing an Excel Worksheet With Correct Data Types
By default, the data type of string/text values from an Excel worksheet is
translated to NVARCHAR(255). This may not be the data type you want for
your columns and this may not be length you want. There are two ways to
override the data type generated by the OLE DB provider when it creates the
table.
The first way is to specify the data types you want for each column in the
SELECT statement using the CAST function:
SELECT CAST([FirstName] AS VARCHAR(20)) AS [FirstName],
CAST([LastName] AS VARCHAR(20)) AS [LastName],
CAST([Address] AS VARCHAR(50)) AS [Address],
CAST([City] AS VARCHAR(30)) AS [City],
CAST([State] AS VARCHAR(2)) AS [State],
CAST([ZIP] AS VARCHAR(10)) AS [ZIP]
INTO [dbo].[Addresses_Temp]
FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=C:\Source\Addresses.xls;IMEX=1',
'SELECT * FROM [Sheet1$]')
The data types of each column will now be based on the data type specified in
the CAST function and not based on the default NVARCHAR(255).
The second way is to first create the destination table, then use the INSERT
statement together with the SELECT statement to import the data from the Excel
worksheet:
CREATE TABLE [dbo].[Addresses_Temp] (
[FirstName] VARCHAR(20),
[LastName] VARCHAR(20),
[Address] VARCHAR(50),
[City] VARCHAR(30),
[State] VARCHAR(2),
[ZIP] VARCHAR(10)
)
GO
INSERT INTO [dbo].[Address_Temp] ( [FirstName], [LastName], [Address], [City], [State], [ZIP] )
SELECT [FirstName], [LastName], [Address], [City], [State], [ZIP]
FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=C:\Source\Addresses.xls;IMEX=1',
'SELECT * FROM [Sheet1$]')
Part
1: Querying an Excel Worksheet
Part 2: Querying an Excel Worksheet Without Header and With Mixed Column Data
Type
|