create procedure SP_ImportExcelFile(
@Source varchar(1000)
, @SourceSheet varchar(100)
, @DestinationTable varchar(100))
as
declare @retval int
--check if file exists
EXEC master..xp_fileexist @Source, @retval output
if @retval = 0
begin
print 'file does not exist.'
return
end
-- check if worksheet exists and if not use Sheet1
if @SourceSheet is null or @SourceSheet = ''
set @SourceSheet = '[Sheet1$]'
else
set @SourceSheet = '[' + ltrim(rtrim(@SourceSheet)) + '$]'
if @DestinationTable is null or @DestinationTable = ''
set @DestinationTable = substring(@SourceSheet, 2, len(@SourceSheet) - 3) + convert(varchar, getdate(), 126)
exec('select * into [' + @DestinationTable + '] from openrowset(''Microsoft.Jet.OLEDB.4.0'', ''Excel 8.0;HDR=YES;Database=' + @Source + ''', ' + @SourceSheet + ')')