Monday, January 7, 2008

Use BCP within ASP.NET, C#

The Bulk Copy Program (BCP) is a command-line utility that ships with SQL Server. You can import / export large amounts of data in / out of SQL.

The BCP utility is accessed from the command prompt. Syntax below:
bcp {dbtable | query} {in | out | queryout | format} datafile
[-n native type] [-c character type]
[-S server name] [-U username]
[-P password] [-T trusted connection]

Remember: When using BCP, the terms are case-sensitive.
-n term specifies native SQL Server format.
-S term enables you to add the server/instance name.
-U term allows you to add the name of the login used to connect to SQL Server.
-P term lets you add the password of the -U switch.
-T term is for establishing a trusted connection to your SQL Server
-c term performs the operation using a character data type. This option does not prompt for each field; it uses char as the storage type, without prefixes and with \t (tab character) as the field separator and \r\n (newline character) as the row terminator
-t field_term specifies the field terminator. The default is \t (tab character). Use this parameter to override the default field terminator.
-r row_term specifies the row terminator. The default is \n (newline character). Use this parameter to override the default row terminator.

Example - C# in .cs file
Process bcp = new Process();
bcp.StartInfo.WorkingDirectory = WorkPath;
bcp.StartInfo.FileName = "bcp";
bcp.StartInfo.Arguments = "datatableName..storedprocedureToRun"
  + " in " //out
  + file.Name
  + @" -c -t ~ -r \n -DATABASE_NAME -Ucredential -Pcredential";
bcp.Start();
bcp.WaitForExit();

No comments: