Use dynamic SQL to fix openrowset parameter and Insert xml files into database under given folder

--SQL CODE TO CREATE SP

Create procedure usp_ImportMultipleFiles2 @filepath nvarchar(500),
@pattern nvarchar(100)
as
set quoted_identifier off

-- Set query files under folder
declare @sql nvarchar(1000)
set @sql ='master.dbo.xp_cmdshell "dir '+@filepath+@pattern +' /b"'

--Retrieve files into temp table #temp
create table #x (name nvarchar(200))
insert #x exec (@sql)
delete from #x where name is NULL
select identity(int,1,1) as ID, name into #temp from #x
drop table #x

declare @max1 int
set @max1 =(select MAX(ID) from #temp)

declare @count1 int
set @count1 =0

declare @filename nvarchar(100)
declare @xml xml

While @count1 <= @max1
begin
set @count1=@count1+1
set @filename = @filepath +(select name from #temp where [id] = @count1)
set @sql ='declare @xml xml
set @xml =( select *
from openrowset(bulk '''+@filename+''' ,single_blob) as xmldata
)
insert XMLData (RawXml) values (@xml)'

exec sp_executesql @sql
end

drop table #temp

--SAMPLE CODE TO CALL ABOVE SP

exec usp_ImportMultipleFiles2 'D:\TEMP\','*.xml'

--NOTE

You can't parametrise or concatenate the parameters of openrowset It is constant values only.

You'll have to use dynamic SQL 

原文地址:https://www.cnblogs.com/mjgb/p/2483404.html