1

SQL Server2008R2データベースのテーブルを更新するプロセスを自動化しようとしています。

クライアントから約20列のデータを含むcsv形式のファイルを取得しています。特定のフォルダにあるファイルをデータベースのテーブルにインポートする必要があります。そこにある場合は、インポートを実行してから、ファイルをベースフォルダーからフォルダーに移動する必要がありProcessedます。

インポートルーチンを実行して、元のテーブルを削除し、新しいテーブルを作成して、データをテーブルにインポートしました。

特定の拡張子を持つ特定のフォルダ内のファイル名を特定する方法を検索しましたが、役立つものは見つかりませんでした。

また、(ストアドプロシージャとは関係なく)ファイルの移動を試みましたが、何かが足りないと思います。これが私が成功せずに試したことです:

    declare @sql varchar (100)
    set @sql = 'move E:\Data\check.csv E:\Data\Processed\ /Y'
    exec master..xp_cmdshell @SQL, NO_OUTPUT 
    go

TIA

4

1 に答える 1

1

I wrote the following stored procedure to list the files in a given path:

ALTER procedure [dbo].[usp__ListFiles_xml] (
    @path varchar(8000),
    @xmldata xml output
)
as
begin
    DECLARE @ProcName varchar(255) = OBJECT_NAME(@@PROCID);

    declare @DirLines table (
        RowNum int identity(1,1) not null,
        line varchar(8000)
    );

    declare @DirCommand varchar(8000) = 'dir /A:-D /n "'+@path+'"';

    insert into @DirLines
        exec xp_cmdshell @DirCOmmand;

    declare @DirName varchar(8000) = (select SUBSTRING(line, 15, 8000) from @DirLines where RowNum = 4);

    delete from @DirLines
    where line is null or isnumeric(LEFT(line, 2)) = 0;

    set @xmldata = (
        select substring(line, 40, 255) as FileName,
               cast(replace(substring(line, 21, 18), ',', '') as bigint) as FileSize,
               cast(left(line, 20) as DateTime) as CreationDateTime,
               @DirName as DirName
        from @DirLines
        for xml raw('Dir'), type
       )

    return;
end;  -- usp__ListFiles_xml

You can select the results into a table, find the file you need, and then continue your load from there by doing:

declare @xmldata xml;

exec usp__ListFiles_xml @FileTemplate, @xmldata output;

declare @Files table (
     FileName varchar(255),
     FileSize bigint,
     CreationDateTime DateTime,
     DirName varchar(8000)
    );
insert into @Files
    select T.c.value('@FileName', 'varchar(255)') as FileName,
           T.c.value('@FileSize', 'bigint') as FileSize,
           T.c.value('@CreationDateTime', 'datetime') as CreationDateTime,
           T.c.value('@DirName', 'varchar(8000)') as DirName
    from @xmldata.nodes('Dir') as T(c);
于 2013-02-08T17:11:20.507 に答える