Question

I have bunch of text files that have phone numbers separated by carriage return. I know these are all numbers. I want to insert all of these numbers into a table in my SQL database. but the problem is the text file starts with the first number; not a column name. It means that I don't know the column name each time I try to insert data.

To clarify this I show you the SQL I've written:

INSERT into dbo.IranCellPhoneNumbers
SELECT PostalCode = null, mobile as Number,CityId= 20
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Text;Database=D:\Projects\Sepanta\ExcelImporter\ExcelImporter\bin\Debug\k1\,
'SELECT * FROM etebari.txt') 

I set postalCode to null because I want the table definitions to match. and set CityId hard coded because I know which city I mean. but the problem is the number column.. it does not match because the text file starts with a number not "mobile" column name.

If I want this code to work, before insertion I have to open up these text files and add "mobile" at the top of list and this is not desirable.

What do you propose?

Was it helpful?

Solution 2

You don't need a column name. Just do this:

INSERT into dbo.IranCellPhoneNumbers
SELECT PostalCode = null, *, CityId= 20
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Text;Database=D:\Projects\Sepanta\ExcelImporter\ExcelImporter\bin\Debug\k1\;HDR=NO',
'SELECT * FROM etebari.txt') 

OTHER TIPS

Try using something similar to the comments in here

http://social.msdn.microsoft.com/forums/en-US/adodotnetdataproviders/thread/cfbe56cc-70b7-462a-b106-0dd9a33304eb

i.e. something along these lines:

"Text;Database=D:\Projects\Sepanta\ExcelImporter\ExcelImporter\bin\Debug\k1\;Extended Properties="Excel 12.0;HDR=No"

There are more samples here:

http://www.codeproject.com/Articles/37055/Working-with-MS-Excel-xls-xlsx-Using-MDAC-and-Oled

OR run this DOS command to add a heading automatically:

COPY HEADERFILE.TXT + YourFile.TXT OUTPUTFILE.TXT

Where HEADERFILE.TXT contains a heading and a carriage return

and it's generally not good table design to have country specific tables, but thats another story.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top