Question : Create Table on the fly for BULK Insert

I have a script that will scan a directory on  a file server looking for csv files in bulk insert them into tables.


However, the tables must already exist in the database. Is there a way that I can write a script that will create the table based on the header information contained on the first line of the csv file?

I want to be able to throw any file into the directory and have my script pick it up and create a table in the database having the same name as the file and then insert all the data from the file.

Please note that I am trying to do this with T-SQL and not with DTS or other external importing procedures.

Answer : Create Table on the fly for BULK Insert

Here is a nasty way to import a textfile into a 'table':

    CREATE TABLE #temp(ID int identity(1,1), TextLine VARCHAR(2000))

    DECLARE @FileName varchar(100)
    DECLARE @ExecCmd varchar(100)

    SET @FileName = 'X:\Path\To\File.txt'
    SET @ExecCmd = 'type ' + @FileName

    INSERT INTO #temp EXEC master.dbo.xp_cmdshell @ExecCmd

You will probably end up with ID =1 for the line containing the header.
From there analyse the columns needed and create the real import table ...

Hope this helps ...

Random Solutions  
 
programming4us programming4us