แสดงบทความที่มีป้ายกำกับ Export Excel to SQL by Store Procedure แสดงบทความทั้งหมด
แสดงบทความที่มีป้ายกำกับ Export Excel to SQL by Store Procedure แสดงบทความทั้งหมด

วันพฤหัสบดีที่ 11 เมษายน พ.ศ. 2556

Export Excel to SQL by Store Procedure


ALTER procedure [dbo].[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 + ‘)’)

ก๊อปโค้ดไปใช้กันได้เลยนะ แล้วเวลา Excecute ก็ Add Job แล้วเลือกแบบ T-SQL
แล้วก็ Excecute Store Procedure ที่เราเพิ่งสร้างไปได้เลยนะค่ะ โดยตัวอย่างก็ประมาณนี้หน่ะค่ะ
EXEC dbGF.dbo.SP_ImportExcelFile ‘C:\Documents and Settings\Administrator\Desktop\a.xls’,
     ’Sheet1′
     ,’a’
ทีนี้ก็เปลี่ยน Path Source File , Sheet , Table Name ได้ตามต้องการเลยนะค่ะ
แล้วที่สำคัญอย่าลืมเลือกที่ Database ที่เราต้องการด้วยนะค่ะ รวมถึงต้องมีตารางด้วยนะ