简体   繁体   中英

Import data from Excel to SQL Server via Stored Procedure

i found a few examples online on how to import excel into sql via vb. but can i do it via stored procedure?

Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;HDR=YES', 
    'SELECT * FROM [SheetName$]')

so like, can i pass in:

('Microsoft.Jet.OLEDB.4.0', 
        'Excel 8.0;Database=D:\testing.xls;HDR=YES', 
        'SELECT * FROM [SheetName$]')

as a parameter to SQL Server SP? or how else can i protect myself from sql injections and other attacks?

DECLARE @bcpCommand varchar(2000), @dt varchar(15), @fn varchar(20), @fn1 varchar(30), @ty char(4) = '.csv', @path varchar(15) = 'C:\sive\'

SELECT @dt = convert(varchar,getdate(),112)

SELECT @fn = 'TblEnquiry_bcp'

SELECT @fn1 = @fn+'_'+@dt+@ty

SELECT @bcpCommand = 'ren '+ @path+@fn + @ty +' ' + @path + @fn1

SELECT @bcpCommand = 'ren '+ @path+@fn + @ty +' ' + @fn1

EXEC xp_cmdshell @bcpCommand

select @bcpCommand = 'bcp "SELECT hc.RegNo VehicleNo, convert(date,hv.DisplayDateTime,112) RunningDate,

       COUNT(1) AS NoofCountPlayed, hv.BoardTransID BoardTransId

       FROM Advertisementlog hv  WITH (NOLOCK)

       INNER JOIN VehiclesM hc WITH (NOLOCK) ON hv.BoardTransID=hc.RTONo

       WHERE convert(varchar(30),displaydatetime,112)>=convert(date,DATEADD(month, DATEDIFF(month, 0, getdate()), 0),112)

       AND convert(varchar(30),displaydatetime,112) <= convert(date,getdate(),112)

       AND hc.RTONo IS NOT NULL AND hc.RTONo <>''

       GROUP BY hc.RegNo, convert(date,hv.DisplayDateTime,112), hv.BoardTransID" queryout C:\Sive\TblEnquiry_bcp.csv -t, -c -T -SHABXC3NKSD -d WeddingVowsUAT'



EXEC xp_cmdshell @bcpCommand

select @bcpCommand = 'copy /b c:\sive\TblEnquiry_Header.csv+c:\sive\tblenquiry_bcp.csv c:\sive\test_bcp.csv'

EXEC xp_cmdshell @bcpCommand

您可以设置一个SSIS程序包,并将其从Excel传输到SQL Server(或平面文件等)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM