Showing posts with label text. Show all posts
Showing posts with label text. Show all posts

Tuesday, March 27, 2012

Bulk Load Text File Using Transact-SQL

I am a newbie (not a developer) trying to load reference tables with SQL script from text files. So far, I know I must use format files but the examples I get are not clear. I cannot find a simple syntax for the format file or the bulk load script. Please help!

Does the following topics help? BOL (SQL Server 2000 or 2005) has lot of examples including format files, statements to use etc.

http://msdn2.microsoft.com/en-us/library/ms189989.aspx

http://msdn2.microsoft.com/en-us/library/aa337544.aspx

http://msdn2.microsoft.com/en-us/library/ms175915.aspx

http://msdn2.microsoft.com/en-us/library/ms178129.aspx

http://msdn2.microsoft.com/en-us/library/ms189848.aspx

http://msdn2.microsoft.com/en-us/library/ms190625.aspx

sql

bulk insert[urgent]

Earlier rowterminator for the text file was '\r\n', I was albe to bulk inser
t
with rowterminator
Now it is changed to '\n', When I use the following syntax
create table #tmp1 ([rows] varchar(5000) )
BULK INSERT #tmp1 from 'c:\test_file.txt'
with
(rowterminator = '\n')
I am getting following error
Server: Msg 4866, Level 17, State 66, Line 1
Bulk Insert fails. Column is too long in the data file for row 1, column 1.
Make sure the field terminator and row terminator are specified correctly.
Server: Msg 7399, Level 16, State 1, Line 1
OLE DB provider 'STREAM' reported an error. The provider did not give any
information about the error.
any help is appreciated.
thanksif u have cygwin installed
try this at command line
c:> type c:\test_file.txt' | wc -l
See what the longest line is. Although you are inserting one reow, see
if a field delimiter might help...\t or something like that or maybe '
' (five spaces)...dirty, but quick...|||> Server: Msg 4866, Level 17, State 66, Line 1
> Bulk Insert fails. Column is too long in the data file for row 1, column
> 1.
> Make sure the field terminator and row terminator are specified correctly.
> Server: Msg 7399, Level 16, State 1, Line 1
> OLE DB provider 'STREAM' reported an error. The provider did not give any
> information about the error.
>
It sounds like your field terminator has changed as well. Double check.|||thanksforhelp (thanksforhelp@.discussions.microsoft.com) writes:
> Earlier rowterminator for the text file was '\r\n', I was albe to bulk
> insert with rowterminator
> Now it is changed to '\n', When I use the following syntax
> create table #tmp1 ([rows] varchar(5000) )
> BULK INSERT #tmp1 from 'c:\test_file.txt'
> with
> (rowterminator = '\n')
> I am getting following error
Only newline as a terminator is somewhat problematic. If memory
serves, I think this works:
EXEC('BULK INSERT #tmp1 from ''c:\test_file.txt''
with (rowterminator = ''' + char(13) + '''')
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||Another option also, if it wont create problems later is to run a batch
file/shell script which converts all your files to dos format...ending
with CHAR(13)+CHAR(10) i.e. ("\r\n")
this is another cygwin option
vim +"argdo set ff=dos" +wqa "Filename"
I use dir c:\directory\*.txt /s/b/ > fileconvert.bat
to create a list of all text files,
then use a macro in a text editor to "quote" the filenames, and add the
vim +"argdo set ff=dos" +wqa command at the front.
I then run fileconvert.bat
and voila... all files in dos format...|||no, this didn't work for me.
thanks for Ur time
"Erland Sommarskog" wrote:

> thanksforhelp (thanksforhelp@.discussions.microsoft.com) writes:
> Only newline as a terminator is somewhat problematic. If memory
> serves, I think this works:
> EXEC('BULK INSERT #tmp1 from ''c:\test_file.txt''
> with (rowterminator = ''' + char(13) + '''')
>
>
> --
> Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
> Books Online for SQL Server 2005 at
> http://www.microsoft.com/technet/pr...oads/books.mspx
> Books Online for SQL Server 2000 at
> http://www.microsoft.com/sql/prodin...ions/books.mspx
>|||thanksforhelp (thanksforhelp@.discussions.microsoft.com) writes:
> no, this didn't work for me.
> thanks for Ur time
Sorry, I was a bit too quick, and I mixed up the numeric codes for
CR and LF. Here is a version that I've actually tested:
create table #tmp1 ([rows] varchar(200) )
declare @.sql varchar(2000)
SELECT @.sql = 'BULK INSERT #tmp1 from ''c:\test_file.txt'''
with (rowterminator = ''' + char(10) + ''')'
EXEC(@.sql)
go
select * from #tmp1
go
drop table #tmp1
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||thanks Erland
but I tried with your code even then I am getting the same error, I am able
load this file with format file with rowterminator \n. But I don't want hard
code the format file in my SP.
Thanks for your time.
"Erland Sommarskog" wrote:

> thanksforhelp (thanksforhelp@.discussions.microsoft.com) writes:
> Sorry, I was a bit too quick, and I mixed up the numeric codes for
> CR and LF. Here is a version that I've actually tested:
> create table #tmp1 ([rows] varchar(200) )
> declare @.sql varchar(2000)
> SELECT @.sql = 'BULK INSERT #tmp1 from ''c:\test_file.txt'''
> with (rowterminator = ''' + char(10) + ''')'
> EXEC(@.sql)
> go
> select * from #tmp1
> go
> drop table #tmp1
>
> --
> Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
> Books Online for SQL Server 2005 at
> http://www.microsoft.com/technet/pr...oads/books.mspx
> Books Online for SQL Server 2000 at
> http://www.microsoft.com/sql/prodin...ions/books.mspx
>|||thanksforhelp (thanksforhelp@.discussions.microsoft.com) writes:
> but I tried with your code even then I am getting the same error, I am
> able load this file with format file with rowterminator \n. But I don't
> want hard code the format file in my SP.
Too bad. It was not because I had changed the size of the temp table?
(I cut it down to varchar(200) to make sure that I would get an error
with my test file, if the rowterminator was never found and BULK INSERT
read it as one row.)
Else would it be possible for you to attach a sample file, or put a
sample at a web site in a zip file?
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||thanks Erland.
I am able to bulk insert it with a format file
with '\n' rowterminator. now I want to know why it is possible with format
file and not with rowterminator and single column.
Since it is company policy I can't post the file in the web
Thank you very much for the time.
"Erland Sommarskog" wrote:

> thanksforhelp (thanksforhelp@.discussions.microsoft.com) writes:
> Too bad. It was not because I had changed the size of the temp table?
> (I cut it down to varchar(200) to make sure that I would get an error
> with my test file, if the rowterminator was never found and BULK INSERT
> read it as one row.)
> Else would it be possible for you to attach a sample file, or put a
> sample at a web site in a zip file?
>
> --
> Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
> Books Online for SQL Server 2005 at
> http://www.microsoft.com/technet/pr...oads/books.mspx
> Books Online for SQL Server 2000 at
> http://www.microsoft.com/sql/prodin...ions/books.mspx
>

Sunday, March 25, 2012

Bulk Insert won't compile if file doesn't exist, no Try Catch either

I first noticed that the try/catch did not seem to work when the text file did not exist and I tried to execute this block of code from a stored proc.

Then, when I tried to compile the proc using a file that did not exist at the time of compilation, I can't even get it to compile.

If I compile, then remove the file, the try/catch does not work.

TRUNCATE TABLE LoadDaily;

BEGIN TRY

BULK INSERT LoadDaily
FROM 'c:\temp\daily.txt'
WITH
(
BATCHSIZE = 100,
FIELDTERMINATOR = '|',
ROWTERMINATOR = '0x0A',
FIRSTROW = 2
);

END TRY
BEGIN CATCH

SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_STATE() as ErrorState,
ERROR_PROCEDURE() as ErrorProcedure,
ERROR_LINE() as ErrorLine,
ERROR_MESSAGE() as ErrorMessage;

END CATCH

Instead of saying "compile" I mean that I can't use either ALTER PROCEDURE or CREATE PROCEDURE when the text file does not exist.

Fortunately, using EXEC works and the try/catch works as directed.

This will be run from a service so I don't think I will have any permissions issues.

I tested in SQL 2000 and did not have any problems editing the SP using EM with a non-existant text file.

It does not work if the format file is missing either.
TRUNCATE TABLE LoadDaily;

BEGIN TRY

DECLARE @.sql nvarchar(300), @.Fname nvarchar(300)

SET @.Fname = 'c:\_temp\daily.txt'

SET @.sql = 'BULK INSERT LoadDaily FROM ''' + @.Fname + ''''
+ ' WITH '
+ ' ( '
+ ' BATCHSIZE = 100, '
+ ' FIELDTERMINATOR = ''|'', '
+ ' ROWTERMINATOR = ''0x0A'', '
+ ' FIRSTROW = 2'
+ ' );'

EXEC (@.sql)


END TRY
BEGIN CATCH

SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_STATE() as ErrorState,
ERROR_PROCEDURE() as ErrorProcedure,
ERROR_LINE() as ErrorLine,
ERROR_MESSAGE() as ErrorMessage;

END CATCH

|||This is a known limitation. TRY...CATCH cannot catch all errors. Some of the errors that happen at compile time can be caught only in the outer TRY..CATCH. This is what you kind of achieved by using dynamic SQL for the BULK INSERT. Please see the TRY...CATCH topic in BOL for more details.|||Sorry, this is a level 16 error so it should be caught by definition (BOL says the range is 10 to 20).

I think I'm more concerned about the regression error. I may be doing something wrong because the environment has changed but I found no way to create the Stored Procedure if the the text file does not exist. I went back and tested it in SQL 2000 and it worked fine.

Since there is now "run as" functionality with EXECUTE, it won't be a big deal but the issue should be addressed.

The new OPENROWSET has the same problem for the text file and the format file.|||Not all errors of a particular severity can be caught. In your examples, these errors are raised at compile time so there is no code execution involved at all for the TRY...CATCH to work. OPENROWSET(BULK) and BULK INSERT pretty much uses the same infrastructure so both will error out if the data file/format file is invalid or missing.|||

OK, let's forget the Try/Catch issue for now.

Just see if you can compile the test proc below in SQL 2005 when daily.txt does NOT exist.

I just found an interesting side effect: Make sure that LoadDaily is a valid table. If LoadDaily is invalid, the code WILL compile.

Now that's really weird.

CREATE PROCEDURE test
AS

BEGIN
BULK INSERT LoadDaily
FROM 'c:\temp\daily.txt'
WITH
(
FIELDTERMINATOR = '|',
ROWTERMINATOR = '\n'
);
END
GO

|||The reason is deferred name resolution. If any object is missing at the time of creation of a stored procedure then the statement is not compiled or parsed completely (note that the syntax is still validated) and deferred until run-time or execution. This explains the behavior you are seeing. This is also true for say references to temporary tables - this is the reason why you can reference temporary tables that are not created in a SP and call it later from another that creates the temporary table or a trigger referencing a temporary table created by a stored procedure that issues the insert/update/delete statement. This is a behavior that we introduced from SQL Server 7.0. Note that this can lead to performance issues due to recompilation of the entire stored procedure at run-time when it hits the statement. This is alleviated to some extent with statement level recompilation in SQL Server 2005. For a more complete discussion, please refer to the whitepaper http://www.microsoft.com/technet/prodtechnol/sql/2005/recomp.mspx.|||

Deferred name resolution really DOES explain why it worked in 2000.

It seems to be partially broken now:
If the table is VALID but the text file is NOT VALID then the proc will NOT compile.

I can't believe that this was the intention. This is simply an external text file so it should not affect compilation.

|||Unfortunately, this is a side-effect of BULK INSERT using the OPENROWSET(BULK) infrastructure internally. OPENROWSET(BULK) validates parameters at compile-time itself and hence the error. This behavior is same as other OPENROWSET commands. For example, if you try OPENROWSET with Jet provider and missing/invalid mdb file you will get same behavior in SQL Server 2000/2005. The reality is that most people will use dynamic SQL since the filenames cannot be parameterized directly so they will not hit the issue.sql

Bulk Insert with text Qualifier

Hi,
I am tring to Bulk Insert a file that has " as text Qualifier. When I bulk
insert this is importing the quotes. I would like to be able to import
without the quotes.
Please let me know if you know how..
Thank you
Sambluefish (bluefish@.discussions.microsoft.com) writes:
> I am tring to Bulk Insert a file that has " as text Qualifier. When I bulk
> insert this is importing the quotes. I would like to be able to import
> without the quotes.
You probably need to use a format file. Without further information,
about your table and data, I can only refer to read about format files
in Books Onlines.
Since the odds are good that Books Online will leave you in a maze
(the topic on format files is not easily digested), you may need further
assistance. In such case, post your table definition and a sample file.
(If the file is wide, over 70 chars wide, please place it as an
attachment, so it does not get wrecked in transport.)
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||Thank you very much for your help in this. I have posted a sample table and
a
data file.
Table:
CREATE TABLE [dbo].[TEST] (
[Col1] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[col2] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
GO
Contenet in my FMT file:
8.0
2
1 SQLCHAR 0 10 "," 1 Col1 SQL_Latin1_General_Cp437_BIN
2 SQLCHAR 0 10 "\r\n" 2 Col2 SQL_Latin1_General_Cp437_BIN
And my data file has following data
"My","World"
I am still unable to get the data in without ". I have checked the format
file sections in books online and google- but without much luck.
Your help in this is appreciated.
Sam
"Erland Sommarskog" wrote:

> bluefish (bluefish@.discussions.microsoft.com) writes:
> You probably need to use a format file. Without further information,
> about your table and data, I can only refer to read about format files
> in Books Onlines.
> Since the odds are good that Books Online will leave you in a maze
> (the topic on format files is not easily digested), you may need further
> assistance. In such case, post your table definition and a sample file.
> (If the file is wide, over 70 chars wide, please place it as an
> attachment, so it does not get wrecked in transport.)
>
> --
> Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
> Books Online for SQL Server 2005 at
> http://www.microsoft.com/technet/pr...oads/books.mspx
> Books Online for SQL Server 2000 at
> http://www.microsoft.com/sql/prodin...ions/books.mspx
>|||bluefish (bluefish@.discussions.microsoft.com) writes:
> Thank you very much for your help in this. I have posted a sample table
> and a data file.
> Table:
> CREATE TABLE [dbo].[TEST] (
> [Col1] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
> [col2] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
> ) ON [PRIMARY]
> GO
> Contenet in my FMT file:
> 8.0
> 2
> 1 SQLCHAR 0 10 "," 1 Col1 SQL_Latin1_General_Cp437_BIN
> 2 SQLCHAR 0 10 "\r\n" 2 Col2 SQL_Latin1_General_Cp437_BIN
> And my data file has following data
> "My","World"
> I am still unable to get the data in without ". I have checked the format
> file sections in books online and google- but without much luck.
Hehe. That's certainly not easily digestable material.
You can do it, but I have to thank former SQL Server MVP Linda W for
learning me the trick. Here is how you format file should look like:
8.0
3
1 SQLCHAR 0 0 "\"" 0 "" ""
2 SQLCHAR 0 0 "\",\"" 1 Col1 SQL_Latin1_General_Cp437_BIN
3 SQLCHAR 0 0 "\"\r\n" 2 Col2 SQL_Latin1_General_Cp437_BIN
First of all, you need to include the " in the delimiter definition. But
the real trick is the addition of a third empty field before the first
". Not that I have a 0 in the database-column number, this column is
not to be imported.
Note: I didn't test this, as the hour is late here. But I hope it
works.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||This worked! Thank you very much!!
Please also convey my thanks to Ms. Linda also.
Sam
"Erland Sommarskog" wrote:

> bluefish (bluefish@.discussions.microsoft.com) writes:
> Hehe. That's certainly not easily digestable material.
> You can do it, but I have to thank former SQL Server MVP Linda W for
> learning me the trick. Here is how you format file should look like:
> 8.0
> 3
> 1 SQLCHAR 0 0 "\"" 0 "" ""
> 2 SQLCHAR 0 0 "\",\"" 1 Col1 SQL_Latin1_General_Cp437_BIN
> 3 SQLCHAR 0 0 "\"\r\n" 2 Col2 SQL_Latin1_General_Cp437_BIN
> First of all, you need to include the " in the delimiter definition. But
> the real trick is the addition of a third empty field before the first
> ". Not that I have a 0 in the database-column number, this column is
> not to be imported.
>
> Note: I didn't test this, as the hour is late here. But I hope it
> works.
> --
> Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
> Books Online for SQL Server 2005 at
> http://www.microsoft.com/technet/pr...oads/books.mspx
> Books Online for SQL Server 2000 at
> http://www.microsoft.com/sql/prodin...ions/books.mspx
>

Bulk Insert with Mirroring

Can anyone suggest a bulk insert solution in a mirroring environment?
Basically, I'd like to import a text or excel file using SSIS.
Do all the "Flat File" and "Excel" data flow sources use bulk inserts?
Just wondering if I would need to use a "staging" table or something like that since bulk inserts won't be logged when dbs are mirrored. I'm assuming I'd be able to import data using the dataflow sources into a sql destination "staging" table, then do a "INSERT INTO [production] SELECT * FROM [staging]". I'm assuming this will be logged (but slow).

Any help would be appreciated.

BULK INSERT is fully logged in FULL mode, so you should not need to do the intermediate step.

Bulk Insert with mid-string newlines

Hi.
I have a text file with several fields. One of these sometimes contains
newline characters. Any fields that do include newline characters are
enclosed with double quotes. What Bulk Insert command line do I need to use
to impot the file without it treating the enclosed newline characters as end
of row delimiters?
Example:
a,b,"c/nld",e
becomes
a b c
d e
where it should be
a b c/nd e
Thanks in advance,
Neil JonesTo clarify, I am looking for a commandline paramter that allows me to
designate a string delimiter, so that everything within the delimiters is
treated as a single string.
"NeilDJones" wrote:

> Hi.
> I have a text file with several fields. One of these sometimes contains
> newline characters. Any fields that do include newline characters are
> enclosed with double quotes. What Bulk Insert command line do I need to us
e
> to impot the file without it treating the enclosed newline characters as e
nd
> of row delimiters?
> Example:
> a,b,"c/nld",e
> becomes
> a b c
> d e
> where it should be
> a b c/nd e
> Thanks in advance,
> Neil Jones|||If you have custom formating, you'd want to use format file.
http://msdn.microsoft.com/library/e...pt_bcp_9yat.asp
-oj
"NeilDJones" <NeilDJones@.discussions.microsoft.com> wrote in message
news:8EBC7227-CD12-4450-93E1-F94E4D5621C6@.microsoft.com...
> Hi.
> I have a text file with several fields. One of these sometimes contains
> newline characters. Any fields that do include newline characters are
> enclosed with double quotes. What Bulk Insert command line do I need to
> use
> to impot the file without it treating the enclosed newline characters as
> end
> of row delimiters?
> Example:
> a,b,"c/nld",e
> becomes
> a b c
> d e
> where it should be
> a b c/nd e
> Thanks in advance,
> Neil Jones|||Thanks for the reply.
Looking at the information for the format file, I still cannot see how I
specify string delimiters, as I am able to do in Excel or Access. Is this
just something that BULK INSERT doesn't handle properly?
Cheers,
Neil
"oj" wrote:

> If you have custom formating, you'd want to use format file.
> http://msdn.microsoft.com/library/e...pt_bcp_9yat.asp
>
>
> --
> -oj
>
> "NeilDJones" <NeilDJones@.discussions.microsoft.com> wrote in message
> news:8EBC7227-CD12-4450-93E1-F94E4D5621C6@.microsoft.com...
>
>|||Sorry for the late reply.
With bulk load (bcp/bulk insert), you can define the column and row
delimiter. However, each must be different from each other (i.e. not
possible when column and row delimiter is defined as \r\n).
If excel/access can format it correctly for you, you might want to send the
data through it first before importing into sqlserver.
-oj
"NeilDJones" <NeilDJones@.discussions.microsoft.com> wrote in message
news:DE2EC0CB-E11F-4DC5-9496-D03482518603@.microsoft.com...
> Thanks for the reply.
> Looking at the information for the format file, I still cannot see how I
> specify string delimiters, as I am able to do in Excel or Access. Is this
> just something that BULK INSERT doesn't handle properly?
> Cheers,
> Neil
> "oj" wrote:
>|||Thanks.
I think I am puttnig this badly.
There is no problem with row or column delimiters. The column delimiter is a
comma, and the row delimiter is newline.
Some of the columns are strings, and these may or may not contain double
quotes ("). If there are double quotes, then everything inside the quotes is
a single string.
The problem arises when there is a newline character within the double
quote-delimited string, eg "Hello\nWorld", which is the string representing
Hello
World
Ideally, this would import as a single string. Excel and Access both do this
fine, but bulk insert doesn't recognise the string delimiter ", and breaks
the string over two lines.
I am hoping someone out there knows how to specify a string delimiter, but
am thinking that there ain't one.
Cheers,
Neil
"oj" wrote:

> Sorry for the late reply.
> With bulk load (bcp/bulk insert), you can define the column and row
> delimiter. However, each must be different from each other (i.e. not
> possible when column and row delimiter is defined as \r\n).
> If excel/access can format it correctly for you, you might want to send th
e
> data through it first before importing into sqlserver.
> --
> -oj
>
> "NeilDJones" <NeilDJones@.discussions.microsoft.com> wrote in message
> news:DE2EC0CB-E11F-4DC5-9496-D03482518603@.microsoft.com...
>
>

Bulk Insert With Identity Field

Hi All,
Can I Bulk Insert to to SQL Table with a Identity Column in it?
My Source is a text file with 17 Columns and My Target is a SQL Server table
with 18 Columns (all 17 column of the source + 1 Identity Column as Primary
KEY).
So In this Situation How can i Bulk Insert to the SQL Table from the text
file. Please give small example if possible.
Also If my SQL table is have 2 More Extra Column Can I Boul Insert from the
above source?
Ex: Total 19 Columns ( all 17 columns of the source text file + 1 Identity
Column + 1 Extra column). If I want to Insert into the 17 columns and I want
the Indetity column to generate auto numbers and the Last Extra Column to be
Filled with Some "Char (1)" Value. Is that Possible?
Thanks for any Help or suggestions
Prabhat
using bulk insert there is a keepidentity parameter, using bcp it is -E...
Both are documented in books on line
Wayne Snyder, MCDBA, SQL Server MVP
Mariner, Charlotte, NC
www.mariner-usa.com
(Please respond only to the newsgroups.)
I support the Professional Association of SQL Server (PASS) and it's
community of SQL Server professionals.
www.sqlpass.org
"Prabhat" <not_a_mail@.hotmail.com> wrote in message
news:OKa8j8unEHA.3868@.TK2MSFTNGP11.phx.gbl...
> Hi All,
> Can I Bulk Insert to to SQL Table with a Identity Column in it?
> My Source is a text file with 17 Columns and My Target is a SQL Server
table
> with 18 Columns (all 17 column of the source + 1 Identity Column as
Primary
> KEY).
> So In this Situation How can i Bulk Insert to the SQL Table from the text
> file. Please give small example if possible.
> Also If my SQL table is have 2 More Extra Column Can I Boul Insert from
the
> above source?
> Ex: Total 19 Columns ( all 17 columns of the source text file + 1 Identity
> Column + 1 Extra column). If I want to Insert into the 17 columns and I
want
> the Indetity column to generate auto numbers and the Last Extra Column to
be
> Filled with Some "Char (1)" Value. Is that Possible?
> Thanks for any Help or suggestions
> Prabhat
>
|||Thanks for the Hint. I have seen that in BOL but did not get any Example.
Can you suggest any site or give me a small Example where the Target table
has a Identity Field but the Source does not have the value for Identity
Column.
Thanks
Prabhat
"Wayne Snyder" <wayne.nospam.snyder@.mariner-usa.com> wrote in message
news:#m#6mmwnEHA.3900@.TK2MSFTNGP10.phx.gbl...[vbcol=seagreen]
> using bulk insert there is a keepidentity parameter, using bcp it is -E...
> Both are documented in books on line
> --
> Wayne Snyder, MCDBA, SQL Server MVP
> Mariner, Charlotte, NC
> www.mariner-usa.com
> (Please respond only to the newsgroups.)
> I support the Professional Association of SQL Server (PASS) and it's
> community of SQL Server professionals.
> www.sqlpass.org
> "Prabhat" <not_a_mail@.hotmail.com> wrote in message
> news:OKa8j8unEHA.3868@.TK2MSFTNGP11.phx.gbl...
> table
> Primary
text[vbcol=seagreen]
> the
Identity[vbcol=seagreen]
> want
to
> be
>

Bulk Insert With Identity Field

Hi All,
Can I Bulk Insert to to SQL Table with a Identity Column in it?
My Source is a text file with 17 Columns and My Target is a SQL Server table
with 18 Columns (all 17 column of the source + 1 Identity Column as Primary
KEY).
So In this Situation How can i Bulk Insert to the SQL Table from the text
file. Please give small example if possible.
Also If my SQL table is have 2 More Extra Column Can I Boul Insert from the
above source?
Ex: Total 19 Columns ( all 17 columns of the source text file + 1 Identity
Column + 1 Extra column). If I want to Insert into the 17 columns and I want
the Indetity column to generate auto numbers and the Last Extra Column to be
Filled with Some "Char (1)" Value. Is that Possible?
Thanks for any Help or suggestions
Prabhatusing bulk insert there is a keepidentity parameter, using bcp it is -E...
Both are documented in books on line
--
Wayne Snyder, MCDBA, SQL Server MVP
Mariner, Charlotte, NC
www.mariner-usa.com
(Please respond only to the newsgroups.)
I support the Professional Association of SQL Server (PASS) and it's
community of SQL Server professionals.
www.sqlpass.org
"Prabhat" <not_a_mail@.hotmail.com> wrote in message
news:OKa8j8unEHA.3868@.TK2MSFTNGP11.phx.gbl...
> Hi All,
> Can I Bulk Insert to to SQL Table with a Identity Column in it?
> My Source is a text file with 17 Columns and My Target is a SQL Server
table
> with 18 Columns (all 17 column of the source + 1 Identity Column as
Primary
> KEY).
> So In this Situation How can i Bulk Insert to the SQL Table from the text
> file. Please give small example if possible.
> Also If my SQL table is have 2 More Extra Column Can I Boul Insert from
the
> above source?
> Ex: Total 19 Columns ( all 17 columns of the source text file + 1 Identity
> Column + 1 Extra column). If I want to Insert into the 17 columns and I
want
> the Indetity column to generate auto numbers and the Last Extra Column to
be
> Filled with Some "Char (1)" Value. Is that Possible?
> Thanks for any Help or suggestions
> Prabhat
>|||Thanks for the Hint. I have seen that in BOL but did not get any Example.
Can you suggest any site or give me a small Example where the Target table
has a Identity Field but the Source does not have the value for Identity
Column.
Thanks
Prabhat
"Wayne Snyder" <wayne.nospam.snyder@.mariner-usa.com> wrote in message
news:#m#6mmwnEHA.3900@.TK2MSFTNGP10.phx.gbl...
> using bulk insert there is a keepidentity parameter, using bcp it is -E...
> Both are documented in books on line
> --
> Wayne Snyder, MCDBA, SQL Server MVP
> Mariner, Charlotte, NC
> www.mariner-usa.com
> (Please respond only to the newsgroups.)
> I support the Professional Association of SQL Server (PASS) and it's
> community of SQL Server professionals.
> www.sqlpass.org
> "Prabhat" <not_a_mail@.hotmail.com> wrote in message
> news:OKa8j8unEHA.3868@.TK2MSFTNGP11.phx.gbl...
> > Hi All,
> >
> > Can I Bulk Insert to to SQL Table with a Identity Column in it?
> >
> > My Source is a text file with 17 Columns and My Target is a SQL Server
> table
> > with 18 Columns (all 17 column of the source + 1 Identity Column as
> Primary
> > KEY).
> >
> > So In this Situation How can i Bulk Insert to the SQL Table from the
text
> > file. Please give small example if possible.
> >
> > Also If my SQL table is have 2 More Extra Column Can I Boul Insert from
> the
> > above source?
> > Ex: Total 19 Columns ( all 17 columns of the source text file + 1
Identity
> > Column + 1 Extra column). If I want to Insert into the 17 columns and I
> want
> > the Indetity column to generate auto numbers and the Last Extra Column
to
> be
> > Filled with Some "Char (1)" Value. Is that Possible?
> >
> > Thanks for any Help or suggestions
> > Prabhat
> >
> >
>sql

Bulk Insert with getdate() ?

Hi,
I have a file that I want to use to bulk insert into a table.
this does not work:
text|text|text|'select getdate()'|text
Is there a way I can put the getdate in there as well?
thanksDon't include the field in the bcp and put a defaulkt on
it.
Bcp into a view which excludes the field if necessary.
>--Original Message--
>Hi,
>I have a file that I want to use to bulk insert into a
table.
>this does not work:
>text|text|text|'select getdate()'|text
>Is there a way I can put the getdate in there as well?
>thanks
>.
>|||"hmc" <nospam@.nospam.com> wrote in message
news:53b5kv0gnpl0th1ag04befajnqhnovhumo@.4ax.com...
> Hi,
> I have a file that I want to use to bulk insert into a table.
> this does not work:
> text|text|text|'select getdate()'|text
> Is there a way I can put the getdate in there as well?
Do it by script as a second step.
Chain the second step to the bulk insert.

BULK INSERT with format file

Hi all,
I have a fixed width text file that I need to import into SQL Server. The
file is very wide and extremely long, so I dont want to go through and
manually create the columns in DTS. I do however want to try and use BULK
INSERT to copy the records into my table. I thought the only way would be t
o
create a format file based on my fixed width text file so it could read the
appropriate columns. The problem is I have never done this and cant seem to
get it working. I guess I need to know if I can use BULK INSERT with a
format file to do this operation or I have to manually size out the columns?
The error I keep getting is some kind of EOF message. I have no idea with I
am creating the format file correctly either, but I made it look exactly wha
t
was on BOL. Thanks in advance for anyones help!!!!Post a few rows of the file, the format file you have created, and the error
msg you are getting...
"Andre" wrote:

> Hi all,
> I have a fixed width text file that I need to import into SQL Server. The
> file is very wide and extremely long, so I dont want to go through and
> manually create the columns in DTS. I do however want to try and use BULK
> INSERT to copy the records into my table. I thought the only way would be
to
> create a format file based on my fixed width text file so it could read th
e
> appropriate columns. The problem is I have never done this and cant seem
to
> get it working. I guess I need to know if I can use BULK INSERT with a
> format file to do this operation or I have to manually size out the column
s?
> The error I keep getting is some kind of EOF message. I have no idea with
I
> am creating the format file correctly either, but I made it look exactly w
hat
> was on BOL. Thanks in advance for anyones help!!!!|||longkimber dba qwestcsql
lessdavid dba qwestcsql
rondtimme dba qwestcsql
8.0
5
1 SQLCHAR 0 4 "\0" 1 lastname SQL_Latin1_General_CP1_CI_AS
2 SQLCHAR 0 5 "\0" 2 firstname SQL_Latin1_General_CP1_CI_A
S
3 SQLCHAR 0 4 "\0" 3 type SQL_Latin1_General_CP1_CI_AS
4 SQLCHAR 0 8 "\0" 4 company SQL_Latin1_General_CP1_CI_AS
5 SQLCHAR 0 3 "\r\n" 5 code SQL_Latin1_General_CP1_CI_AS
"CBretana" wrote:
> Post a few rows of the file, the format file you have created, and the err
or
> msg you are getting...
> "Andre" wrote:
>|||OK, You said this was su[pposed to be a "Fixed Width" data file, if so,
then there ARE NO field terminators, enter an empty string "" for the
terminators in all but the last field. Second, The BCP automatically adds
the Carriage Return, when you specify the new Line... (\n) so not specify
(\r\n) or you will get two carriage returns...
Finally, the three data rows you passed DO NOT have the same number of
characters in them... a fixed width file MUST have exactly the same number
of characters (BYTES) In each row... R U Sure you have a fixed width file '
"Andre" wrote:
> longkimber dba qwestcsql
> lessdavid dba qwestcsql
> rondtimme dba qwestcsql
> 8.0
> 5
> 1 SQLCHAR 0 4 "\0" 1 lastname SQL_Latin1_General_CP1_CI_AS
> 2 SQLCHAR 0 5 "\0" 2 firstname SQL_Latin1_General_CP1_CI_A
S
> 3 SQLCHAR 0 4 "\0" 3 type SQL_Latin1_General_CP1_CI_AS
> 4 SQLCHAR 0 8 "\0" 4 company SQL_Latin1_General_CP1_CI_AS
> 5 SQLCHAR 0 3 "\r\n" 5 code SQL_Latin1_General_CP1_CI_AS
>
> "CBretana" wrote:
>|||Oh I was typing in the data and added a character by accident. Yes there ar
e
no field terminators. I was giving a file that looks this like with a data
dictionary with how long each field should be. OK, I will do the empty
string, but what do I put for the last line? Also, I cant write out the
entire error message, but it says at the end some kind of EOF error message.
If you give me your email I can take a screen shot and send it to you.
Thanks for all your assistance.
"CBretana" wrote:
> OK, You said this was su[pposed to be a "Fixed Width" data file, if so,
> then there ARE NO field terminators, enter an empty string "" for the
> terminators in all but the last field. Second, The BCP automatically add
s
> the Carriage Return, when you specify the new Line... (\n) so not specify
> (\r\n) or you will get two carriage returns...
> Finally, the three data rows you passed DO NOT have the same number of
> characters in them... a fixed width file MUST have exactly the same numbe
r
> of characters (BYTES) In each row... R U Sure you have a fixed width file
'
> "Andre" wrote:
>|||Yes, send me the actual file, or if it's too big, the first thousand lines o
r
so... And the format file, and the error msg screen shot...
Send to cbretana@.areteind.com
"Andre" wrote:
> Oh I was typing in the data and added a character by accident. Yes there
are
> no field terminators. I was giving a file that looks this like with a dat
a
> dictionary with how long each field should be. OK, I will do the empty
> string, but what do I put for the last line? Also, I cant write out the
> entire error message, but it says at the end some kind of EOF error messag
e.
> If you give me your email I can take a screen shot and send it to you.
> Thanks for all your assistance.
> "CBretana" wrote:
>|||In addition to the other poster's comments there is one gotcha with BULK
INSERT and format files. Your format file must contain a hard return at the
end or else you will get an error. This error is different depending on the
format version, but it often makes no sense.
So if you are editing your format file in notepad go to the end and hit "Ent
er."
Seriously.
> longkimber dba qwestcsql
> lessdavid dba qwestcsql
> rondtimme dba qwestcsql
> 8.0
> 5
> 1 SQLCHAR 0 4 "\0" 1 lastname SQL_Latin1_General_CP1_CI_AS
> 2 SQLCHAR 0 5 "\0" 2 firstname SQL_Latin1_General_CP1_CI_A
S
> 3 SQLCHAR 0 4 "\0" 3 type SQL_Latin1_General_CP1_CI_AS
> 4 SQLCHAR 0 8 "\0" 4 company SQL_Latin1_General_CP1_CI_AS
> 5 SQLCHAR 0 3 "\r\n" 5 code SQL_Latin1_General_CP1_CI_AS
> "CBretana" wrote:
>|||There is a shortcut to creating format files that I discovered and have used
religiously ever since.
Create a dummy DTS package and create a "Bulk Insert" task on the package.
On the properties page for the task, select the table (you will need a SQL
connection task first), then click "Use Format File" and then click the
Generate button. Browse to your input file and enter a name for the format
file. Then click next and follow the prompts. You will have to indicate
where the fields end (same dialogs as when importing a flat file to Excel).
After you finish the 'generate' dialogs...the format file will be created
and you can delete the Bulk Insert icon from the DTS package or just close
DTS without saving the package at all.
At this point, if you need to add, modify or delete fields...it is easy to
do manually because all the goofy formatting requirements of this file are
taken care of.
"Andre" <Andre@.discussions.microsoft.com> wrote in message
news:CC4A24C5-D822-4FE2-A724-58D094D298AE@.microsoft.com...
> Hi all,
> I have a fixed width text file that I need to import into SQL Server. The
> file is very wide and extremely long, so I dont want to go through and
> manually create the columns in DTS. I do however want to try and use BULK
> INSERT to copy the records into my table. I thought the only way would be
to
> create a format file based on my fixed width text file so it could read
the
> appropriate columns. The problem is I have never done this and cant seem
to
> get it working. I guess I need to know if I can use BULK INSERT with a
> format file to do this operation or I have to manually size out the
columns?
> The error I keep getting is some kind of EOF message. I have no idea with
I
> am creating the format file correctly either, but I made it look exactly
what
> was on BOL. Thanks in advance for anyones help!!!!

Bulk Insert with Added Columns

Hi, I'd like to do a bulk copy insert inside a dts package but the table i'm
inserting to has more columns than the text file. I know you can change the
format file to take care of this, but how do you insert actual values into
those extra columns instead of just NULLS? The values for those extra column
s
are uniquely identified by the text file.
What I could do is do a bulk insert and then run an execute sql command
afterwards which updates the table by replacing the NULL values with actual
values. However, this db is multi-user with each user having different value
s
to insert, so if two imports are done at the same time, someone could be
updating the rows of another person's import. Locking the table is also not
a
possibility because the imports take a long time and we don't want one user
waiting on another one to finish.
Right now, I'm using an ActiveX script in a transform data task in the DTS
package. So there's two transformations going on in that task: one is the
copy column from the text file, and another is adding values to the extra
columns. This works well, however, it requires row by row processing and thu
s
it takes over 3 times longer than a bulk insert.
Does anyone have a solution to setting values of extra columns in a bulk
insert? Any help is appreciated. Thanks!Where do those extra values come from?
ML|||These extra values are global variables in the dts package
"ML" wrote:

> Where do those extra values come from?
>
> ML|||In that case you can design a set-based solution. You need something like th
is:
1) you need access to the file - one way to achieve this is linking the file
as a linked server. Read more on this here:
http://msdn.microsoft.com/library/d... />
a_8gqa.asp
http://msdn.microsoft.com/library/d...ma_ini_file.asp
2) you need access to your global variables - the best way would be to
create a procedure that accesses the linked file and accepts the values of
those global variables as parameters;
3) in your procedure you then combine the values from the source file and
the values from the DTS, and insert them into the destination table(s).
You could even use a folder-sniffer to start the job automatically, as soon
as the source file becomes available in the source folder.
ML

Thursday, March 22, 2012

Bulk Insert Unicode

Good day,

We are using bulk insert with a formatfile to load a text file into sqlexpress. One field in the text file contains non-ascii (unicode) charaters and the corresponding database field is nvarchar.

When the record and row are specified in the format file as:

<FIELD ID="23" xsi:type="CharTerm" TERMINATOR="\t" MAX_LENGTH="400" COLLATION="Latin1_General_CI_AS"/>
<COLUMN SOURCE="23" NAME="FullName" xsi:type="SQLNVARCHAR"/>

the value "Boca Curá" gets imported as "Boca Cur??". This is true even with datafiletype set to widenative or widechar, and/or codepage set to raw or acp.

When the field is specfied in the record section of the format file as NCharTerm, the bulk insert terminates immediately with:

Msg 4863, Level 16, State 1, Server MINT\SQLEXPRESS, Line 1
Bulk load data conversion error (truncation) for row 2, column 23 (FullName).

This is true regardless of which bulk insert options specified.

What could be going wrong and how can we address it?

Thanks in advance...

Hi,

I see it's been a while since you posted this, but I have just run into this same issue today and I was wondering if you were able to resolve it gracefully?

regards

|||

Hi knightEknight!

We solved this with MS using a developer support incident. I should have updated this post when the information was fresh! Just went back through my notes and the readme for the project, and the solution was to convert the input file from UTF8 text encoding to ANSI text encoding. This is a Save As option in Notepad and most text editors. If you have a large file and need some C# code to do this, let me know....

|||Thanks! My input comes from various sources and I've pretty much concluded the same thing. I'll just have to find a way to convert all the input to ANSI. - Regards|||

Here is a C# example:

// utf8 in, ansi out

StreamReader inStream = File.OpenText(@."E:\Data\DEM\Panama\panama_canal_final.txt");

FileStream outStream = File.Create(@."E:\Data\DEM\Panama\panama_canal_fsubset.txt");

Encoding ansi = Encoding.Default;

string inLine;

byte[] outBytes;

while (true)

{

inLine = inStream.ReadLine();

if (inLine == null)

break;

outBytes = ansi.GetBytes(inLine + "\r\n");

outStream.Write(outBytes, 0, outBytes.Length);

}

inStream.Close();

outStream.Close();

|||

Instead of converting your files to ANSI as suggested you could also fix your delimiter problem for Unicode files. The TERMINATOR should be '\t\0' instead of just '\t' for tabs and '\r\0\n\0' for the row delimiter if you are using standard CR+LF.

Regards,

Lars

sql

Bulk Insert Unicode

Good day,

We are using bulk insert with a formatfile to load a text file into sqlexpress. One field in the text file contains non-ascii (unicode) charaters and the corresponding database field is nvarchar.

When the record and row are specified in the format file as:

<FIELD ID="23" xsi:type="CharTerm" TERMINATOR="\t" MAX_LENGTH="400" COLLATION="Latin1_General_CI_AS"/>
<COLUMN SOURCE="23" NAME="FullName" xsi:type="SQLNVARCHAR"/>

the value "Boca Curá" gets imported as "Boca Cur??". This is true even with datafiletype set to widenative or widechar, and/or codepage set to raw or acp.

When the field is specfied in the record section of the format file as NCharTerm, the bulk insert terminates immediately with:

Msg 4863, Level 16, State 1, Server MINT\SQLEXPRESS, Line 1
Bulk load data conversion error (truncation) for row 2, column 23 (FullName).

This is true regardless of which bulk insert options specified.

What could be going wrong and how can we address it?

Thanks in advance...

Hi,

I see it's been a while since you posted this, but I have just run into this same issue today and I was wondering if you were able to resolve it gracefully?

regards

|||

Hi knightEknight!

We solved this with MS using a developer support incident. I should have updated this post when the information was fresh! Just went back through my notes and the readme for the project, and the solution was to convert the input file from UTF8 text encoding to ANSI text encoding. This is a Save As option in Notepad and most text editors. If you have a large file and need some C# code to do this, let me know....

|||Thanks! My input comes from various sources and I've pretty much concluded the same thing. I'll just have to find a way to convert all the input to ANSI. - Regards|||

Here is a C# example:

// utf8 in, ansi out

StreamReader inStream = File.OpenText(@."E:\Data\DEM\Panama\panama_canal_final.txt");

FileStream outStream = File.Create(@."E:\Data\DEM\Panama\panama_canal_fsubset.txt");

Encoding ansi = Encoding.Default;

string inLine;

byte[] outBytes;

while (true)

{

inLine = inStream.ReadLine();

if (inLine == null)

break;

outBytes = ansi.GetBytes(inLine + "\r\n");

outStream.Write(outBytes, 0, outBytes.Length);

}

inStream.Close();

outStream.Close();

|||

Instead of converting your files to ANSI as suggested you could also fix your delimiter problem for Unicode files. The TERMINATOR should be '\t\0' instead of just '\t' for tabs and '\r\0\n\0' for the row delimiter if you are using standard CR+LF.

Regards,

Lars

Bulk Insert Unicode

Good day,

We are using bulk insert with a formatfile to load a text file into sqlexpress. One field in the text file contains non-ascii (unicode) charaters and the corresponding database field is nvarchar.

When the record and row are specified in the format file as:

<FIELD ID="23" xsi:type="CharTerm" TERMINATOR="\t" MAX_LENGTH="400" COLLATION="Latin1_General_CI_AS"/>
<COLUMN SOURCE="23" NAME="FullName" xsi:type="SQLNVARCHAR"/>

the value "Boca Curá" gets imported as "Boca Cur??". This is true even with datafiletype set to widenative or widechar, and/or codepage set to raw or acp.

When the field is specfied in the record section of the format file as NCharTerm, the bulk insert terminates immediately with:

Msg 4863, Level 16, State 1, Server MINT\SQLEXPRESS, Line 1
Bulk load data conversion error (truncation) for row 2, column 23 (FullName).

This is true regardless of which bulk insert options specified.

What could be going wrong and how can we address it?

Thanks in advance...

Hi,

I see it's been a while since you posted this, but I have just run into this same issue today and I was wondering if you were able to resolve it gracefully?

regards

|||

Hi knightEknight!

We solved this with MS using a developer support incident. I should have updated this post when the information was fresh! Just went back through my notes and the readme for the project, and the solution was to convert the input file from UTF8 text encoding to ANSI text encoding. This is a Save As option in Notepad and most text editors. If you have a large file and need some C# code to do this, let me know....

|||Thanks! My input comes from various sources and I've pretty much concluded the same thing. I'll just have to find a way to convert all the input to ANSI. - Regards|||

Here is a C# example:

// utf8 in, ansi out

StreamReader inStream = File.OpenText(@."E:\Data\DEM\Panama\panama_canal_final.txt");

FileStream outStream = File.Create(@."E:\Data\DEM\Panama\panama_canal_fsubset.txt");

Encoding ansi = Encoding.Default;

string inLine;

byte[] outBytes;

while (true)

{

inLine = inStream.ReadLine();

if (inLine == null)

break;

outBytes = ansi.GetBytes(inLine + "\r\n");

outStream.Write(outBytes, 0, outBytes.Length);

}

inStream.Close();

outStream.Close();

Bulk Insert Unicode

Good day,

We are using bulk insert with a formatfile to load a text file into sqlexpress. One field in the text file contains non-ascii (unicode) charaters and the corresponding database field is nvarchar.

When the record and row are specified in the format file as:

<FIELD ID="23" xsi:type="CharTerm" TERMINATOR="\t" MAX_LENGTH="400" COLLATION="Latin1_General_CI_AS"/>
<COLUMN SOURCE="23" NAME="FullName" xsi:type="SQLNVARCHAR"/>

the value "Boca Curá" gets imported as "Boca Cur??". This is true even with datafiletype set to widenative or widechar, and/or codepage set to raw or acp.

When the field is specfied in the record section of the format file as NCharTerm, the bulk insert terminates immediately with:

Msg 4863, Level 16, State 1, Server MINT\SQLEXPRESS, Line 1
Bulk load data conversion error (truncation) for row 2, column 23 (FullName).

This is true regardless of which bulk insert options specified.

What could be going wrong and how can we address it?

Thanks in advance...

Hi,

I see it's been a while since you posted this, but I have just run into this same issue today and I was wondering if you were able to resolve it gracefully?

regards

|||

Hi knightEknight!

We solved this with MS using a developer support incident. I should have updated this post when the information was fresh! Just went back through my notes and the readme for the project, and the solution was to convert the input file from UTF8 text encoding to ANSI text encoding. This is a Save As option in Notepad and most text editors. If you have a large file and need some C# code to do this, let me know....

|||Thanks! My input comes from various sources and I've pretty much concluded the same thing. I'll just have to find a way to convert all the input to ANSI. - Regards|||

Here is a C# example:

// utf8 in, ansi out

StreamReader inStream = File.OpenText(@."E:\Data\DEM\Panama\panama_canal_final.txt");

FileStream outStream = File.Create(@."E:\Data\DEM\Panama\panama_canal_fsubset.txt");

Encoding ansi = Encoding.Default;

string inLine;

byte[] outBytes;

while (true)

{

inLine = inStream.ReadLine();

if (inLine == null)

break;

outBytes = ansi.GetBytes(inLine + "\r\n");

outStream.Write(outBytes, 0, outBytes.Length);

}

inStream.Close();

outStream.Close();

Bulk Insert Unicode

Good day,
We are using bulk insert with a formatfile to load a text file into
sqlexpress. One field in the text file contains non-ascii (unicode)
charaters and the corresponding database field is nvarchar.
When the record and row are specified in the format file as:
<FIELD ID=3D"23" xsi:type=3D"CharTerm" TERMINATOR=3D"\t" MAX_LENGTH=3D"400"
COLLATION=3D"Latin1_General_CI_AS"/>
<COLUMN SOURCE=3D"23" NAME=3D"FullName" xsi:type=3D"SQLNVARCHAR"/>
the value "Boca Cur=E1" gets imported as "Boca Cur=C3=A1". This is true
even with datafiletype set to widenative or widechar, and/or codepage
set to raw or acp.
When the field is specfied in the record section of the format file as
NCharTerm, the bulk insert terminates immediately with:
Msg 4863, Level 16, State 1, Server MINT\SQLEXPRESS, Line 1
Bulk load data conversion error (truncation) for row 2, column 23
(FullName).
This is true regardless bulk insert options specified.
What could be going wrong and how can we address it?
Thanks in advance...Hi
Can you specify SQLNVARCHAR(50) for example? If I remember well it truncates
the string if you do not specify a length.As it is NVARCHAR , so it is like
NVARCHAR(2)
<rgreene@.icanmarine.com> wrote in message
news:1143039002.249599.122720@.g10g2000cwb.googlegroups.com...
Good day,
We are using bulk insert with a formatfile to load a text file into
sqlexpress. One field in the text file contains non-ascii (unicode)
charaters and the corresponding database field is nvarchar.
When the record and row are specified in the format file as:
<FIELD ID="23" xsi:type="CharTerm" TERMINATOR="\t" MAX_LENGTH="400"
COLLATION="Latin1_General_CI_AS"/>
<COLUMN SOURCE="23" NAME="FullName" xsi:type="SQLNVARCHAR"/>
the value "Boca Cur" gets imported as "Boca Curá". This is true
even with datafiletype set to widenative or widechar, and/or codepage
set to raw or acp.
When the field is specfied in the record section of the format file as
NCharTerm, the bulk insert terminates immediately with:
Msg 4863, Level 16, State 1, Server MINT\SQLEXPRESS, Line 1
Bulk load data conversion error (truncation) for row 2, column 23
(FullName).
This is true regardless bulk insert options specified.
What could be going wrong and how can we address it?
Thanks in advance...|||Hi Uri. Thanks for the quick reply.
When I use NCharTerm in the record section of the formatfile and
SQLNVARCHAR(200) in the row section I get:
Msg 4858, Level 16, State 1, Server MINT\SQLEXPRESS, Line 1
Line 49 in format file "C:\Documents and Settings\rgreene\My
Documents\PlaceName
s\format.xml": bad value SQLNVARCHAR(200) for attribute "xsi:type".
Any other ideas?|||Well, can you show us a format file? Is it a XML file?
<rgreene@.icanmarine.com> wrote in message
news:1143039873.112229.184880@.g10g2000cwb.googlegroups.com...
> Hi Uri. Thanks for the quick reply.
> When I use NCharTerm in the record section of the formatfile and
> SQLNVARCHAR(200) in the row section I get:
> Msg 4858, Level 16, State 1, Server MINT\SQLEXPRESS, Line 1
> Line 49 in format file "C:\Documents and Settings\rgreene\My
> Documents\PlaceName
> s\format.xml": bad value SQLNVARCHAR(200) for attribute "xsi:type".
> Any other ideas?
>|||Here is the original XML format file (the one that imports, but
changes, the unicode text):
<?xml version="1.0"?>
<BCPFORMAT
xmlns="http://schemas.microsoft.com/sqlserver/2004/bulkload/format"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<RECORD>
<FIELD ID="1" xsi:type="CharTerm" TERMINATOR="\t" MAX_LENGTH="5"/>
<FIELD ID="2" xsi:type="CharTerm" TERMINATOR="\t" MAX_LENGTH="12"/>
<FIELD ID="3" xsi:type="CharTerm" TERMINATOR="\t" MAX_LENGTH="12"/>
<FIELD ID="4" xsi:type="CharTerm" TERMINATOR="\t" MAX_LENGTH="30"/>
<FIELD ID="5" xsi:type="CharTerm" TERMINATOR="\t" MAX_LENGTH="30"/>
<FIELD ID="6" xsi:type="CharTerm" TERMINATOR="\t" MAX_LENGTH="7"/>
<FIELD ID="7" xsi:type="CharTerm" TERMINATOR="\t" MAX_LENGTH="8"/>
<FIELD ID="8" xsi:type="CharTerm" TERMINATOR="\t" MAX_LENGTH="4"/>
<FIELD ID="9" xsi:type="CharTerm" TERMINATOR="\t" MAX_LENGTH="7"/>
<FIELD ID="10" xsi:type="CharTerm" TERMINATOR="\t" MAX_LENGTH="2"
COLLATION="Latin1_General_CI_AS"/>
<FIELD ID="11" xsi:type="CharTerm" TERMINATOR="\t" MAX_LENGTH="10"
COLLATION="Latin1_General_CI_AS"/>
<FIELD ID="12" xsi:type="CharTerm" TERMINATOR="\t" MAX_LENGTH="5"/>
<FIELD ID="13" xsi:type="CharTerm" TERMINATOR="\t" MAX_LENGTH="4"
COLLATION="Latin1_General_CI_AS"/>
<FIELD ID="14" xsi:type="CharTerm" TERMINATOR="\t" MAX_LENGTH="4"
COLLATION="Latin1_General_CI_AS"/>
<FIELD ID="15" xsi:type="CharTerm" TERMINATOR="\t" MAX_LENGTH="400"
COLLATION="Latin1_General_CI_AS"/>
<FIELD ID="16" xsi:type="CharTerm" TERMINATOR="\t"
MAX_LENGTH="12"/>
<FIELD ID="17" xsi:type="CharTerm" TERMINATOR="\t" MAX_LENGTH="4"
COLLATION="Latin1_General_CI_AS"/>
<FIELD ID="18" xsi:type="CharTerm" TERMINATOR="\t" MAX_LENGTH="2"
COLLATION="Latin1_General_CI_AS"/>
<FIELD ID="19" xsi:type="CharTerm" TERMINATOR="\t" MAX_LENGTH="6"
COLLATION="Latin1_General_CI_AS"/>
<FIELD ID="20" xsi:type="CharTerm" TERMINATOR="\t"
MAX_LENGTH="128"/>
<FIELD ID="21" xsi:type="CharTerm" TERMINATOR="\t"
MAX_LENGTH="128"/>
<FIELD ID="22" xsi:type="CharTerm" TERMINATOR="\t" MAX_LENGTH="400"
COLLATION="Latin1_General_CI_AS"/>
<FIELD ID="23" xsi:type="CharTerm" TERMINATOR="\t" MAX_LENGTH="400"
COLLATION="Latin1_General_CI_AS"/>
<FIELD ID="24" xsi:type="CharTerm" TERMINATOR="\t" MAX_LENGTH="400"
COLLATION="Latin1_General_CI_AS"/>
<FIELD ID="25" xsi:type="CharTerm" TERMINATOR="\r\n"
MAX_LENGTH="24"/>
</RECORD>
<ROW>
<COLUMN SOURCE="1" NAME="RegionCode" xsi:type="SQLTINYINT"/>
<COLUMN SOURCE="2" NAME="UniqueFeatureIdentifier"
xsi:type="SQLINT"/>
<COLUMN SOURCE="3" NAME="UniqueNameIdentifier" xsi:type="SQLINT"/>
<COLUMN SOURCE="4" NAME="Lat" xsi:type="SQLFLT8"/>
<COLUMN SOURCE="5" NAME="Lon" xsi:type="SQLFLT8"/>
<COLUMN SOURCE="10" NAME="FeatureClassificationCode"
xsi:type="SQLNCHAR"/>
<COLUMN SOURCE="11" NAME="FeatureDesignationCode"
xsi:type="SQLNVARCHAR"/>
<COLUMN SOURCE="12" NAME="PopulatedPlaceClassification"
xsi:type="SQLTINYINT"/>
<COLUMN SOURCE="13" NAME="PrimaryCountryCode"
xsi:type="SQLNVARCHAR"/>
<COLUMN SOURCE="14" NAME="ADM1Code" xsi:type="SQLNVARCHAR"/>
<COLUMN SOURCE="15" NAME="ADM2" xsi:type="SQLNVARCHAR"/>
<COLUMN SOURCE="16" NAME="Dimension" xsi:type="SQLINT"/>
<COLUMN SOURCE="17" NAME="SecondaryCountryCode"
xsi:type="SQLNVARCHAR"/>
<COLUMN SOURCE="18" NAME="NameType" xsi:type="SQLNCHAR"/>
<COLUMN SOURCE="19" NAME="LanguageCode" xsi:type="SQLNVARCHAR"/>
<COLUMN SOURCE="22" NAME="SortName" xsi:type="SQLNVARCHAR"/>
<COLUMN SOURCE="23" NAME="FullName" xsi:type="SQLNVARCHAR()"/>
<COLUMN SOURCE="24" NAME="FullNameND" xsi:type="SQLNVARCHAR"/>
<COLUMN SOURCE="25" NAME="ModificationDate"
xsi:type="SQLDATETIME"/>
</ROW>
</BCPFORMAT>

BULK INSERT to a Temporary Table

I wanto to execute a BULK INSERT command into a Temporary Table:
CREATE TABLE #textfile (line varchar(8000))
-- Read the text file into the temp table
BULK INSERT #textfile FROM 'c\Projects.txt'
But when I execute this command a recieve the following error message:
"The current user is not the database or object owner of table
'#textfile'. Cannot perform SET operation."
Im logged in a Microsoft SQL Server 2000, with a login account that
belogs to the role db_owner of the database Im working, but does not
belong to the role db_owner of tempdb database. Is it necessary?
What am I doing wrong?
Thanks,
Paulo
*** Sent via Developersdex http://www.codecomments.com ***
Hi
You may wantr to check out
http://support.microsoft.com/default...b;en-us;302621 regarding
permissions needed.
John
"Paulo Andre Ortega Ribeiro" wrote:

> I wanto to execute a BULK INSERT command into a Temporary Table:
> CREATE TABLE #textfile (line varchar(8000))
> -- Read the text file into the temp table
> BULK INSERT #textfile FROM 'c\Projects.txt'
> But when I execute this command a recieve the following error message:
> "The current user is not the database or object owner of table
> '#textfile'. Cannot perform SET operation."
> I4m logged in a Microsoft SQL Server 2000, with a login account that
> belogs to the role db_owner of the database I4m working, but does not
> belong to the role db_owner of tempdb database. Is it necessary?
> What am I doing wrong?
> Thanks,
> Paulo
>
> *** Sent via Developersdex http://www.codecomments.com ***
>

BULK INSERT to a Temporary Table

I wanto to execute a BULK INSERT command into a Temporary Table:
CREATE TABLE #textfile (line varchar(8000))
-- Read the text file into the temp table
BULK INSERT #textfile FROM 'c\Projects.txt'
But when I execute this command a recieve the following error message:
"The current user is not the database or object owner of table
'#textfile'. Cannot perform SET operation."
Im logged in a Microsoft SQL Server 2000, with a login account that
belogs to the role db_owner of the database Im working, but does not
belong to the role db_owner of tempdb database. Is it necessary?
What am I doing wrong?
Thanks,
Paulo
*** Sent via Developersdex http://www.codecomments.com ***Hi
You may wantr to check out
http://support.microsoft.com/defaul...kb;en-us;302621 regarding
permissions needed.
John
"Paulo Andre Ortega Ribeiro" wrote:

> I wanto to execute a BULK INSERT command into a Temporary Table:
> CREATE TABLE #textfile (line varchar(8000))
> -- Read the text file into the temp table
> BULK INSERT #textfile FROM 'c\Projects.txt'
> But when I execute this command a recieve the following error message:
> "The current user is not the database or object owner of table
> '#textfile'. Cannot perform SET operation."
> I4m logged in a Microsoft SQL Server 2000, with a login account that
> belogs to the role db_owner of the database I4m working, but does not
> belong to the role db_owner of tempdb database. Is it necessary?
> What am I doing wrong?
> Thanks,
> Paulo
>
> *** Sent via Developersdex http://www.codecomments.com ***
>

BULK INSERT to a Temporary Table

I wanto to execute a BULK INSERT command into a Temporary Table:
CREATE TABLE #textfile (line varchar(8000))
-- Read the text file into the temp table
BULK INSERT #textfile FROM 'c\Projects.txt'
But when I execute this command a recieve the following error message:
"The current user is not the database or object owner of table
'#textfile'. Cannot perform SET operation."
I´m logged in a Microsoft SQL Server 2000, with a login account that
belogs to the role db_owner of the database I´m working, but does not
belong to the role db_owner of tempdb database. Is it necessary?
What am I doing wrong?
Thanks,
Paulo
*** Sent via Developersdex http://www.developersdex.com ***Hi
You may wantr to check out
http://support.microsoft.com/default.aspx?scid=kb;en-us;302621 regarding
permissions needed.
John
"Paulo Andre Ortega Ribeiro" wrote:
> I wanto to execute a BULK INSERT command into a Temporary Table:
> CREATE TABLE #textfile (line varchar(8000))
> -- Read the text file into the temp table
> BULK INSERT #textfile FROM 'c\Projects.txt'
> But when I execute this command a recieve the following error message:
> "The current user is not the database or object owner of table
> '#textfile'. Cannot perform SET operation."
> I4m logged in a Microsoft SQL Server 2000, with a login account that
> belogs to the role db_owner of the database I4m working, but does not
> belong to the role db_owner of tempdb database. Is it necessary?
> What am I doing wrong?
> Thanks,
> Paulo
>
> *** Sent via Developersdex http://www.developersdex.com ***
>

Bulk Insert Statement

Hi All

I have a text file (sample below) i am bulk loading it into a staging table, the problem i am getting is the data is being loaded and scrambling the rows and I need the data to be imported exactly the same row by row

040207,"1007","","3319506/"
031207,"1509",">","US78016"
031207,"1509",">","AA004388"
031207,"1509",">","COMD88"
031207,"1509",">","US78016"
031207,"1509",">","AA001601"
031207,"1509",">","COMD88"
031207,"1510",">","US78016"
031207,"1510",">","AA004337"
031207,"1510",">","COMD88"
031307,"1138",">","US78016"
031307,"1139",">","AA004293"
031307,"1139",">","COMD81"


set nocount on
bulk insert data_load_stage.dbo.
from 'C:\load\CM07.txt'
with ( fieldterminator = ',')

missing a switch i think

thanks in advance

rich

Richie,

You'll need to add a clustered index to your staging table and then add the ORDER hint to your BULK INSERT statement (both matching the ordering of the input file).

From BULK INSERT in BOL:

ORDER ( { column [ ASC | DESC ] } [ ,... n ] )

Specifies how the data in the data file is sorted. Bulk load operation performance is improved if the data loaded is sorted according to the clustered index on the table. If the data file is sorted in a different order, or there is no clustered index on the table, the ORDER clause is ignored. The column names supplied must be valid columns in the destination table. By default, the bulk insert operation assumes the data file is unordered.

sql