insert many .txt files (daily) to sql server 2008 table - sql-server

I am trying to import .txt files daily into sql server 2008 table and I want to automate it
so in steps:
1- I receive 2 files daily with name hazem.log.date and hazem.log.date2
2- I need to have a way to import them daily and automatically
3- I will use the job, but which command or query should be used in this case?

Try running below through SQLServer jobs..
BULK INSERT dbo.ImportTest
FROM 'C:\ImportData.txt' --replace name of your files
WITH ( FIELDTERMINATOR =',', FIRSTROW = 2 )
you also can use
bcp dbo.ImportTest in 'C:\ImportData.txt' -T -SserverName\instanceName
For Mutiple files..you can do like this..
1.Create a stored proc first..
Create procedure usp_ImportMultipleFilesBCP #servername varchar(128),
#DatabaseName varchar(128), #filepath varchar(500), #pattern varchar(100),
#TableName varchar(128)
as
declare #query varchar(1000)
declare #max1 int
declare #count1 int
Declare #filename varchar(100)
set #count1 =0
create table #x (name varchar(200))
set #query ='master.dbo.xp_cmdshell "dir '+#filepath+#pattern +' /b"'
insert #x exec (#query)
delete from #x where name is NULL
select identity(int,1,1) as ID, name into #y from #x
drop table #x
set #max1 = (select max(ID) from #y)
--print #max1
--print #count1
--select * from #y
While #count1 <= #max1
begin
set #count1=#count1+1
set #filename = (select name from #y where [id] = #count1)
set #Query ='bcp "'+ #databasename+'.dbo.'+#Tablename + '"
in "'+ #Filepath+#Filename+'" -S' + #servername + ' -T -c -r\n -t,'
set #Query = 'MASTER.DBO.xp_cmdshell '+ "'"+ #query +"'"
--print #query
EXEC ( #query)
insert into logtable (query) select #query
end
2.Now run above sp to import all files of desired extension
Exec usp_ImportMultipleFilesBCP 'SQL','Bank','c:\Myimport\','*.csv','Account'--table account
Note:
You will need to enable Xp_cmdshell
References:
https://www.mssqltips.com/sqlservertip/1207/different-options-for-importing-data-into-sql-server/
http://www.databasejournal.com/features/mssql/article.php/3325701/Import-multiple-Files-to-SQL-Server-using-T-SQL.htm

Related

Exporting to txt file not allowing more than 255 characters

Below is the script that i have used which shows that i have used BCP process and some shell script to generate the extracts. we need to take the data from sql table and dump as it is in table to flat file. So these can be used to load in hive tables and qlick apps for users to have a look at the data.
ALTER Procedure [dbo].[GenerateEAPExtracts] #tblName NVARCHAR(MAX), #filePath VARCHAR(255)
As
BEGIN
IF OBJECT_ID('tempdb..#Temp1') IS NOT NULL
BEGIN
Drop table #Temp1
END
--DECLARE #tblName NVARCHAR(MAX) = 'BMI.BMI_Invites'
DECLARE #SchemaName NVARCHAR(50)
DECLARE #tbl varchar(100)
DECLARE #DBName varchar(100)
SET #tbl= Replace(#tblname,(Left(#tblname,(LEN(#tblname)-(charindex('.',reverse(#tblname))-1)))),'');
SET #SchemaName= SUBSTRING(#tblName,1,LEN(Left(#tblname,(LEN(#tblname)-(charindex('.',reverse(#tblname))-1))))-1);
DECLARE #SQL NVARCHAR(MAX)=''
DECLARE #SQL1 NVARCHAR(MAX)=''
DECLARE #ColConvert NVARCHAR(MAX)=''
DECLARE #ColName NVARCHAR(MAX)=''
DECLARE #ColName1 NVARCHAR(MAX)=''
DECLARE #ColName2 NVARCHAR(MAX)=''
DECLARE #Dt NVARCHAR(MAX)=''
DECLARE #I INT=1, #COUNT INT;
Create table #Temp1(
ID INT IDENTITY(1,1),
[DBName] [nvarchar](255) NULL,
[TableName] [nvarchar](255) NULL,
[Attributes] [nvarchar](MAX) NULL,
[DataType] [nvarchar](MAX) NULL,
[TceMdf_Dt] [date] NULL
)
SET #SQL = 'INSERT INTO #Temp1 select TABLE_CATALOG as [DBName],
Table_Name as [TableName],
Column_name as [Attributes],
DATA_TYPE as [DataType],
getdate() as [TceMdf_Dt]
from Information_schema.columns where Table_Schema ='''+ #SchemaName +''' AND table_name = '''+#tbl+''''
print #SQL
--EXEC SP_EXECUTESQL #SQL
EXEC(#SQL)
SELECT #SQL1='Select #totCnt= count(1) FROM Information_schema.columns where Table_Schema ='''+ #SchemaName +''' AND table_name = '''+#tbl+''''
print #SQL1
EXECUTE sp_executesql #SQL1, N'#totCnt int OUTPUT', #totCnt=#COUNT OUTPUT
WHILE #I <= #COUNT
BEGIN
SELECT #ColName = Attributes FROM #Temp1 WHERE ID = #I AND [TableName]=#tbl;
SELECT #DBName = DBName FROM #Temp1 WHERE ID = #I AND [TableName]=#tbl;
SELECT #Dt= DataType FROM #Temp1 WHERE ID = #I AND [TableName]=#tbl AND [Attributes]=#ColName
IF #Dt ='Date' or #Dt='Datetime' or #Dt='Decimal' or #Dt='Int' or #Dt='Float' or #Dt='datetime2' or #Dt='Numeric' or #Dt='Real' or #Dt='bit' or #Dt='tinyint'
BEGIN
SET #ColConvert='convert(varchar(25),['+#ColName+'],120)'
--EXECUTE sp_executesql #ColConvert
SET #ColName2 = #ColName2 + ',' + #ColConvert
--EXECUTE sp_executesql #ColName2
END
ELSE
BEGIN
SET #ColName2 = #ColName2 + ',' + '['+#ColName+']'
--EXECUTE sp_executesql #ColName2
END
SET #ColName1 = #ColName1 +''''+''''+','+''''+''''+ #ColName
--EXECUTE sp_executesql #ColName1
SET #I=#I+1;
END
SET #ColName1=RIGHT(#ColName1, LEN(#ColName1) - 3) + ''''''
SET #ColName2=LTRIM(RTRIM(RIGHT(#ColName2, LEN(#ColName2) - 1)))
--print #ColName1
--print #ColName2
--DECLARE #filePath VARCHAR(255)
DECLARE #fileName VARCHAR(255)
DECLARE #sqlCommand VARCHAR(MAX)
DECLARE #sqlCommand1 VARCHAR(MAX)
DECLARE #sqlCommand2 VARCHAR(MAX)
DECLARE #qry nvarchar(max)='(SELECT MaxCDate from '+#DBName+'.config.EAP_Extracts where TableName= '''''+ #tbl +''''')'
print #qry
--exec(#qry)
--SET #filePath = 'C:\'
SET #fileName = #tbl + '_'
+ CONVERT(VARCHAR, GETDATE(), 112) + '.csv'
set #sqlCommand = 'SQLCMD.EXE -S LocalHost -d TCE_WW -E -h -1 -s"|" -W -Q "set nocount on;SELECT ' +#ColName1+ ' ; Select ' +#ColName2+ ' FROM '+#DBName+'.' +#tblName+ ''
print(#sqlCommand)
set #sqlCommand1 =' where TceMdf_Dt > '+ #qry +''
set #sqlCommand2 ='" -o "'+#filePath+#fileName+'" -f 65001'
--declare #chkQry varchar(max) = #sqlCommand+#sqlCommand1+#sqlCommand2
--print(#chkQry)
Update config.EAP_Extracts Set [SqlMaxQuery]=#sqlCommand+#sqlCommand1+#sqlCommand2 where TableName=''+#tbl+''
declare #CommandString varchar(max)= (select distinct 'EXEC xp_cmdshell '+''''+[SqlMaxQuery]+'''' from config.EAP_Extracts where TableName=''+#tbl+'')
--declare #CommandString varchar(max)= 'EXEC xp_cmdshell ' + ''''+#chkQry+''''
print #CommandString
EXEC (#CommandString)
declare #SQLQuery varchar(max)='Update '+#DBName+'.config.EAP_Extracts Set MaxCDate=(Select Max(TceMdf_Dt) from '+ #tblName+') where TableName='''+#tbl+''''
--EXEC xp_cmdshell 'bcp "SELECT ''update_action'',''UserName'',''lastupdate'',''Quote_Num'',''Region'',''ExternalDataReference'',''TceLd_Dt'',''TceMdf_Dt'',''Record_Status'' ; Select LTRIM(RTRIM[update_action]),LTRIM(RTRIM[UserName]),LTRIM(RTRIM[lastupdate]),LTRIM(RTRIM[Quote_Num]),LTRIM(RTRIM[Region]),LTRIM(RTRIM[ExternalDataReference]),convert(varchar(25),LTRIM(RTRIM[TceLd_Dt]),120),convert(varchar(25),LTRIM(RTRIM[TceMdf_Dt]),120),LTRIM(RTRIM[Record_Status]) FROM TCE_WW.BMI.BMI_Invites where TceMdf_Dt > (SELECT MaxCDate from TCE_WW.config.EAP_Extracts where TableName= 'BMI_Invites')" queryout "C:\BMI_Invites_20190722.txt" -T -c -q -y 0 -t"|"'
exec (#SQLQuery)
print(#SQLQuery)
Drop table #Temp1
END

SQL Server: executing part of a stored procedure that is in one database against all other databases

I am trying to run this procedure in order to select a bunch of results from multiple tables in another databases and put everything into one temp table. I can only use this one stored procedure and can't put it into another database
I tried using this here, but it didn't work and gave me the error
'Must declare the scalar variable "#lcsqlcmd"'. #lcsqlcmd
I already declared though any help?
EXEC master..sp_MSforeachdb
IF DB_ID(''?'') > 4
BEGIN
INSERT INTO #TempTable
EXECUTE (#lcsqlcmd)
END
The easiest way is to build the actual T-SQL string you want to run on each database and execute that. The other databases have no knowledge of the stored procedure you are trying to run.
The proper syntax in your case would be something like this.
CREATE TABLE #TempTable( [DBID] INT, DBName SYSNAME )
DECLARE #ForEachCommand VARCHAR( MAX ), #lcsqlcmd VARCHAR( MAX )
SET #lcsqlcmd = 'USE [?]; SELECT DB_ID() AS [DBID], DB_NAME( DB_ID()) AS DBName'
SET #ForEachCommand =
'IF DB_ID(''?'') > 4
BEGIN
insert into #TempTable
EXEC sp_executesql N''' + #lcsqlcmd + '''
end'
print #ForEachCommand
EXECUTE master.sys.sp_MSforeachdb #ForEachCommand
SELECT * FROM #TempTable
See: http://weblogs.sqlteam.com/joew/archive/2008/08/27/60700.aspx
Note: generally it is not a good idea to build your code around undocumented procedures.
The code that does not use undocumented procedure is below:
SELECT database_id, name AS DBName
INTO #Databases
FROM sys.databases WHERE database_id > 4
CREATE TABLE #TempTable( [DBID] INT, DBName SYSNAME )
DECLARE #lcsqlcmd NVARCHAR( MAX ), #Command NVARCHAR( MAX )
SET #lcsqlcmd = 'USE [?]; SELECT DB_ID() AS [DBID], DB_NAME( DB_ID()) AS DBName'
DECLARE #DBName SYSNAME
SET #DBName = ( SELECT TOP 1 DBName FROM #Databases ORDER BY DBName )
WHILE NOT #DBName IS NULL
BEGIN
SET #Command = REPLACE( #lcsqlcmd, '?', #DBName )
insert into #TempTable
EXEC sp_executesql #Command
SET #DBName = ( SELECT TOP 1 DBName FROM #Databases WHERE DBName > #DBName ORDER BY DBName )
END
SELECT * FROM #TempTable
DROP TABLE #Databases

Insert filename during bulk load in SQL Server

DECLARE #SQL_BULK VARCHAR(MAX)
SET #SQL_BULK = 'BULK INSERT [dbo].[Table]
FROM ''' + #BatchFileName + '''
WITH
(
FIRSTROW = 2,
FIELDTERMINATOR = ''\t'',
ROWTERMINATOR = ''0x0a''
)'
EXEC (#SQL_BULK)
I have this code to do a bulk load. Works fine, but I would like to have the #BatchFileName also in there as a column (each row contains the same value).
Is this possible during the bulk load? Or how can I add it later on in a separate function?
Thanks in advance
i use this script to iterate and bulkinsert files in directory:
create table #x (name varchar(200))
DECLARE #query varchar (1000),#conta int ,#query2 varchar (1000),#NOME varchar(50)
set #conta=1
set #query ='master.dbo.xp_cmdshell "dir '+'C:\directoryname'+'*.csv' +' /b"'
insert #x exec (#query)
delete from #x where name is NULL
select identity(int,1,1) as ID, name into #y from #x
drop table #x
WHILE #conta<221 --number of files
BEGIN
SELECT #NOME=name FROM #y WHERE ID=#conta
set #Query2 ='BULK INSERT [dbo].[tablename] FROM '+ '''C:\directoryname'+#NOME+'''
WITH (
FIELDTERMINATOR = '','',ROWTERMINATOR = ''0x0a'')'
SELECT #query2
exec (#Query2)
set #conta=#conta+1
END
drop table #y

Import Multiple CSV Files to SQL Server from a Folder

I have a folder called "Dump." This folder consists of various .CSV Files.
The folder Location is 'C:\Dump'
I want to Import the contents of these files into SQL Server.
I want the rough code along with proper comments so that I understand it.
I have tried a few codes that I found on the Net. But they haven't quite worked out for me for some strange reason.
The steps I would like to have are
Step 1: Copy all the File Names in the folder to a Table
Step 2: Iterate through the table and copy the data from the files using Bulk Insert.
Someone do please help me out on this one. Thanks a lot in advance :)
--BULK INSERT MULTIPLE FILES From a Folder
--a table to loop thru filenames drop table ALLFILENAMES
CREATE TABLE ALLFILENAMES(WHICHPATH VARCHAR(255),WHICHFILE varchar(255))
--some variables
declare #filename varchar(255),
#path varchar(255),
#sql varchar(8000),
#cmd varchar(1000)
--get the list of files to process:
SET #path = 'C:\Dump\'
SET #cmd = 'dir ' + #path + '*.csv /b'
INSERT INTO ALLFILENAMES(WHICHFILE)
EXEC Master..xp_cmdShell #cmd
UPDATE ALLFILENAMES SET WHICHPATH = #path where WHICHPATH is null
--cursor loop
declare c1 cursor for SELECT WHICHPATH,WHICHFILE FROM ALLFILENAMES where WHICHFILE like '%.csv%'
open c1
fetch next from c1 into #path,#filename
While ##fetch_status <> -1
begin
--bulk insert won't take a variable name, so make a sql and execute it instead:
set #sql = 'BULK INSERT Temp FROM ''' + #path + #filename + ''' '
+ ' WITH (
FIELDTERMINATOR = '','',
ROWTERMINATOR = ''\n'',
FIRSTROW = 2
) '
print #sql
exec (#sql)
fetch next from c1 into #path,#filename
end
close c1
deallocate c1
--Extras
--delete from ALLFILENAMES where WHICHFILE is NULL
--select * from ALLFILENAMES
--drop table ALLFILENAMES
This will give you separate tables for each file.
--BULK INSERT MULTIPLE FILES From a Folder
drop table allfilenames
--a table to loop thru filenames drop table ALLFILENAMES
CREATE TABLE ALLFILENAMES(WHICHPATH VARCHAR(255),WHICHFILE varchar(255))
--some variables
declare #filename varchar(255),
#path varchar(255),
#sql varchar(8000),
#cmd varchar(1000)
--get the list of files to process:
SET #path = 'D:\Benihana\backup_csv_benihana_20191128032207_part_1\'
SET #cmd = 'dir ' + #path + '*.csv /b'
INSERT INTO ALLFILENAMES(WHICHFILE)
EXEC Master..xp_cmdShell #cmd
UPDATE ALLFILENAMES SET WHICHPATH = #path where WHICHPATH is null
delete from ALLFILENAMES where WHICHFILE is null
--SELECT replace(whichfile,'.csv',''),* FROM dbo.ALLFILENAMES
--cursor loop
declare c1 cursor for SELECT WHICHPATH,WHICHFILE FROM ALLFILENAMES where WHICHFILE like '%.csv%' order by WHICHFILE desc
open c1
fetch next from c1 into #path,#filename
While ##fetch_status <> -1
begin
--bulk insert won't take a variable name, so make a sql and execute it instead:
set #sql =
'select * into '+ Replace(#filename, '.csv','')+'
from openrowset(''MSDASQL''
,''Driver={Microsoft Access Text Driver (*.txt, *.csv)}''
,''select * from '+#Path+#filename+''')'
print #sql
exec (#sql)
fetch next from c1 into #path,#filename
end
close c1
deallocate c1
For Step 1 Maybe you can look at:
http://www.sql-server-performance.com/forum/threads/copying-filenames-to-sql-table.11546/
or
How to list files inside a folder with SQL Server
and then Step 2
How to cast variables in T-SQL for bulk insert?
HTH
You might need to enable the xp_cmdshell first:
sp_configure 'show advanced options', '1'
RECONFIGURE
go
sp_configure 'xp_cmdshell', '1'
RECONFIGURE
go
And, to enable ad_hoc,
sp_configure 'show advanced options', 1;
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO
To solve step 1, xp_dirtree can also be used to list all files and folders.
Keep in mind that it is an undocumented function. Security precautions must be considered. Intentionally crafted filenames could be an intrusion vector.
In python you can use d6tstack which makes this simple
import d6tstack
import glob
c = d6tstack.combine_csv.CombinerCSV(glob.glob('*.csv'))
c.to_mssql_combine('mssql+pymssql://usr:pwd#localhost/db', 'tablename')
See SQL examples. It also deals with data schema changes, creates table and allows you to preprocess data. It leverages BULK INSERT so should be just as fast.
to expand upon the answer by SarangArd you can replace temp with the following if your file name matches your table name.
' + Left(#filename, Len(#filename)-4) + '
This code will create a new table per CSV file that is imported.
Best to populate empty database from CSV files.
CREATE TABLE ALLFILENAMES
(
WHICHPATH VARCHAR(255)
,WHICHFILE VARCHAR(255)
)
DECLARE #filename VARCHAR(255),
#path VARCHAR(255),
#sql VARCHAR(8000),
#cmd VARCHAR(1000)
SET #path = 'L:\DATA\SOURCE\CSV\' --PATH TO YOUR CSV FILES (CHANGE TO YOUR PATH)
SET #cmd = 'dir ' + #path + '*.csv /b'
INSERT INTO ALLFILENAMES(WHICHFILE)
EXEC Master..xp_cmdShell #cmd
UPDATE ALLFILENAMES
SET WHICHPATH = #path
WHERE WHICHPATH IS NULL
DECLARE c1 CURSOR
FOR SELECT WHICHPATH
,WHICHFILE
FROM ALLFILENAMES
WHERE WHICHFILE LIKE '%.csv%'
OPEN c1
FETCH NEXT FROM c1 INTO #path,
#filename
WHILE ##fetch_status <> -1
BEGIN
CREATE TABLE #Header
(
HeadString NVARCHAR(MAX)
)
DECLARE #Columns NVARCHAR(MAX) = ''
DECLARE #Query NVARCHAR(MAX) = ''
DECLARE #QUERY2 NVARCHAR(MAX) = ''
DECLARE #HeaderQuery NVARCHAR(MAX) = ''
SELECT #HeaderQuery = #HeaderQuery + 'bulk insert #Header from ''' + #path + #filename + '''
with(firstrow=1,lastrow=1)'
EXEC (#HeaderQuery)
SELECT #Columns = (SELECT QUOTENAME(value) + ' nvarchar(max)' + ','
FROM #Header
CROSS APPLY STRING_SPLIT(HeadString,',') FOR xml PATH(''))
IF ISNULL(#Columns,'') <> ''
BEGIN
SET #Columns = LEFT(#Columns,LEN(#Columns) - 1)
SELECT #Query = #Query + 'CREATE TABLE ' + Replace(#filename,'.csv','') + ' (' + replace(#Columns,'"','') + ')'
PRINT #Query
EXEC (#QUERY)
END
SELECT #QUERY2 = #QUERY2 + 'bulk insert ' + replace(Replace(#filename,'.csv',''),'.TPS','') + ' from ''' + #path + #filename + '''
with(firstrow=2,FORMAT=''csv'',FIELDTERMINATOR='','',ROWTERMINATOR=''\n'')'
EXEC (#QUERY2)
DROP TABLE #Header
FETCH NEXT FROM c1 INTO #path,
#filename
END
CLOSE c1
DEALLOCATE c1

Rename files on disk with t-sql

I am using T-SQL
I have a few excel files located here: C:\MyFiles\
I want to remove all the apostrophes in the file names in that directory.
Now to remove apostrophes one would use code like this.
update MyTable
set FileName= replace(FileName, '''', '')
If I had all the file name in the DB it would be easy to do with the code above. But I need to update the file names that are located on disk.
How would I go about doing this with T-SQL?
It must be T-SQL because I need to add it to my existing code in my Stored Procedure.
SET NOCOUNT ON;
CREATE TABLE #FileList
(
FileID INT IDENTITY(1, 1)
,Line VARCHAR(512)
)
CREATE TABLE #temp
(
isFileThere BIT
,isDirectory BIT
,parentDirExists BIT
)
DECLARE #Command VARCHAR(1024)
, #RowCount INT
, #counter INT
, #FileName VARCHAR(1024)
, #FileExists BIT
SET #Command = 'dir C:\MyFiles\ /A-D /B'
PRINT #Command
INSERT #FileList
EXEC master.dbo.xp_cmdshell #Command
DELETE FROM #FileList
WHERE Line IS NULL
SELECT #RowCount = COUNT(*)
FROM [#FileList]
SET #counter = 1
WHILE ( #counter <= #RowCount )
BEGIN
SELECT #FileName = [Line]
FROM [#FileList]
WHERE [FileID] = #counter
SET #Command = 'C:\MyFiles\' + #FileName + ''
PRINT #Command
INSERT [#temp]
EXEC master.dbo.xp_fileExist #Command
SELECT #FileExists = [isFileThere]
FROM [#temp]
IF #FileExists = 1
AND CHARINDEX('''', #FileName) > 0
SET #Command = 'REN "C:\MyFiles\' + #FileName + '" "'
+ REPLACE(#FileName, '''', '') + '"'
ELSE
SET #Command = ''
SET #counter = #counter + 1
PRINT #Command
IF LEN(#Command) > 0
EXEC master.dbo.xp_cmdshell #Command
END
DROP TABLE #FileList
DROP TABLE [#temp]
First you need to enable xp_cmdshell
EXEC sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
EXEC sp_configure 'xp_cmdshell', 1
GO
RECONFIGURE
GO
Then you can use sp_cmdshell to retrieve the files names from the directory
Declare #Directory TABLE (Files Varchar(MAX))
Declare #File TABLE (Name varchar(MAX))
INSERT INTO #Directory
EXEC XP_CMDSHELL 'DIR "D:"'
Insert into #File
Select reverse(LEFT(reverse(Files),charindex(' ' ,reverse(Files)))) from #Directory
Select * from #FILE
Now you get the file names in the table variable #FILE and use function like replace or your own custom function to replace apostrophes with the exact filename
Try this it will work for you
1) Create a sp as mentioned below
CREATE PROCEDURE dbo.ListPathsXML
#FileSpec VARCHAR(2000),
#order VARCHAR (80) = '/O-D',--sort by date time oldest first
#xmlFileList XML OUTPUT
AS
DECLARE #myfiles TABLE (MyID INT IDENTITY(1,1) PRIMARY KEY, FullPath VARCHAR(2000))
DECLARE #CommandLine VARCHAR(4000)
IF #order IS NOT NULL -- abort if the order is silly
BEGIN
SELECT #CommandLine =LEFT('dir "' + #FileSpec + '" /A-D /B /S '+#order,4000)
INSERT INTO #MyFiles (FullPath)
EXECUTE xp_cmdshell #CommandLine
DELETE FROM #MyFiles WHERE fullpath IS NULL
OR fullpath = 'File Not Found'
END
SET #xmlFileList = (SELECT fullpath FROM #MyFiles
FOR
XML PATH('thefile'),
ROOT('thefiles'),
TYPE)
2) and then give a name of directory where you want to replace the name of files
DECLARE #LotsOfText NVARCHAR(MAX),
#ii INT,
#iiMax INT,
#File VARCHAR(2000),
#Command NVARCHAR(4000)
DECLARE #files TABLE (MyID INT IDENTITY(1,1) PRIMARY KEY, [Path] VARCHAR(2000))
DECLARE #FileList XML
EXECUTE ListPathsXML 'D:\QAconfig\',
DEFAULT , #XMLFileList = #FileList OUTPUT
INSERT INTO #files(path)
SELECT x.thefile.value('fullpath[1]', 'varchar(2000)') AS [path]
FROM #FileList.nodes('//thefiles/thefile') AS x ( thefile )
--don't look at the current errorlog!
SELECT #ii=1, #iiMax=MAX(MyID) FROM #Files
WHILE #ii<=#iiMax
BEGIN
SELECT #File= [path] FROM #files WHERE MyID=#ii
print #File
SELECT #command='EXEC master..xp_cmdshell' + '''MOVE '+ Replace(#FILE,'''','''''') + ' ' +REPLACE(#FILE,'''','') +''''
print #command
EXECUTE sp_ExecuteSQL #command--, N'#lotsOfText nvarchar(max) output ',#lotsoftext output
SELECT #ii=#ii+1
END

Resources