Home Forums SQL Server 7,2000 Backups Export table data to textfiles with filename the same as tablename RE: Export table data to textfiles with filename the same as tablename

  • Hi,

    For 1) and 2), you could use a script like below. For 3), you should give some more details about what you want exactly. You can put the below script in a stored procedure, and schedule it as a job. For the current script to run, the destination folder should exists.

     

    Bert

     

    /*          The script          */

    declare @tbl varchar(255), @filename varchar(255),@bcp varchar(1024)

    declare tbl cursor

    local FAST_FORWARD

    for

    -- select here the table names and the filenames to export

    select filename = 'D:\temp\' + db_name() + '\' + name + '.txt' ,

           tblname  = db_name()+ '.' + user_name(uid) + '.' + name

    from sysobjects

    where type = 'U'

    open tbl

    goto nexttbl

    while @@fetch_status = 0

    begin

       -- bcp options :

       -- -q     : to allow blancs and other special characters in the @tbl

       -- -c     : bulc copy using \t as coluln delimiter and \n as row delimiter

       -- -C ACP : use the ISO-8859-1 charset

       -- -T     : use trusted connections

       set @bcp = 'bcp "' + @tbl + '" out "' + @filename + '" -q -c -C ACP -T'

     

       exec master.dbo.xp_cmdshell @bcp

       nexttbl:

       fetch tbl into @filename,@tbl

    end

    close tbl

    deallocate tbl