473,406 Members | 2,698 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Replace Single quotes to double quote or space.

Expand|Select|Wrap|Line Numbers
  1. Below is the code i have written for my ETL purpose. 
  2.  
  3. #region Help:  Introduction to the script task
  4. /* The Script Task allows you to perform virtually any operation that can be accomplished in
  5.  * a .Net application within the context of an Integration Services control flow. 
  6.  * 
  7.  * Expand the other regions which have "Help" prefixes for examples of specific ways to use
  8.  * Integration Services features within this script task. */
  9. #endregion
  10.  
  11.  
  12. #region Namespaces
  13. using System;
  14. using System.Data;
  15. using Microsoft.SqlServer.Dts.Runtime;
  16. using System.Windows.Forms;
  17. using System.IO;
  18. using System.Data.SqlClient;
  19.  
  20. #endregion
  21.  
  22. namespace ST_41636843287142e79bcaa204deb7adb0
  23. {
  24.     /// <summary>
  25.     /// ScriptMain is the entry point class of the script.  Do not change the name, attributes,
  26.     /// or parent of this class.
  27.     /// </summary>
  28.     [Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
  29.     public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
  30.     {
  31.         private object Replace;
  32.         #region Help:  Using Integration Services variables and parameters in a script
  33.         /* To use a variable in this script, first ensure that the variable has been added to 
  34.          * either the list contained in the ReadOnlyVariables property or the list contained in 
  35.          * the ReadWriteVariables property of this script task, according to whether or not your
  36.          * code needs to write to the variable.  To add the variable, save this script, close this instance of
  37.          * Visual Studio, and update the ReadOnlyVariables and 
  38.          * ReadWriteVariables properties in the Script Transformation Editor window.
  39.          * To use a parameter in this script, follow the same steps. Parameters are always read-only.
  40.          * 
  41.          * Example of reading from a variable:
  42.          *  DateTime startTime = (DateTime) Dts.Variables["System::StartTime"].Value;
  43.          * 
  44.          * Example of writing to a variable:
  45.          *  Dts.Variables["User::myStringVariable"].Value = "new value";
  46.          * 
  47.          * Example of reading from a package parameter:
  48.          *  int batchId = (int) Dts.Variables["$Package::batchId"].Value;
  49.          *  
  50.          * Example of reading from a project parameter:
  51.          *  int batchId = (int) Dts.Variables["$Project::batchId"].Value;
  52.          * 
  53.          * Example of reading from a sensitive project parameter:
  54.          *  int batchId = (int) Dts.Variables["$Project::batchId"].GetSensitiveValue();
  55.          * */
  56.  
  57.         #endregion
  58.  
  59.         #region Help:  Firing Integration Services events from a script
  60.         /* This script task can fire events for logging purposes.
  61.          * 
  62.          * Example of firing an error event:
  63.          *  Dts.Events.FireError(18, "Process Values", "Bad value", "", 0);
  64.          * 
  65.          * Example of firing an information event:
  66.          *  Dts.Events.FireInformation(3, "Process Values", "Processing has started", "", 0, ref fireAgain)
  67.          * 
  68.          * Example of firing a warning event:
  69.          *  Dts.Events.FireWarning(14, "Process Values", "No values received for input", "", 0);
  70.          * */
  71.         #endregion
  72.  
  73.         #region Help:  Using Integration Services connection managers in a script
  74.         /* Some types of connection managers can be used in this script task.  See the topic 
  75.          * "Working with Connection Managers Programatically" for details.
  76.          * 
  77.          * Example of using an ADO.Net connection manager:
  78.          *  object rawConnection = Dts.Connections["Sales DB"].AcquireConnection(Dts.Transaction);
  79.          *  SqlConnection myADONETConnection = (SqlConnection)rawConnection;
  80.          *  //Use the connection in some code here, then release the connection
  81.          *  Dts.Connections["Sales DB"].ReleaseConnection(rawConnection);
  82.          *
  83.          * Example of using a File connection manager
  84.          *  object rawConnection = Dts.Connections["Prices.zip"].AcquireConnection(Dts.Transaction);
  85.          *  string filePath = (string)rawConnection;
  86.          *  //Use the connection in some code here, then release the connection
  87.          *  Dts.Connections["Prices.zip"].ReleaseConnection(rawConnection);
  88.          * */
  89.         #endregion
  90.  
  91.  
  92.         /// <summary>
  93.         /// This method is called when this script task executes in the control flow.
  94.         /// Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
  95.         /// To open Help, press F1.
  96.         /// </summary>
  97.         public void Main()
  98.         {
  99.             // TODO: Add your code here
  100.             string datetime = DateTime.Now.ToString("yyyyMMddHHmmss"); 
  101.             try
  102.             {
  103.  
  104.                 //Declare Variables
  105.                 string SourceFolder = Dts.Variables["User::SourceFolder"].Value.ToString();
  106.                 string FileExtension = Dts.Variables["User::FileExtension"].Value.ToString();
  107.                 string FileDelimiter = Dts.Variables["User::FileDelimiter"].Value.ToString();
  108.                 string ArchiveFolder = Dts.Variables["User::ArchiveFolder"].Value.ToString();
  109.                 string ColumnsDataTypes = Dts.Variables["User::ColumnsDataTypes"].Value.ToString();
  110.                 string SchemaName = Dts.Variables["User::SchemaName"].Value.ToString();
  111.                 //string ColumnList = "";
  112.                 if (FileDelimiter == "Pipe")
  113.                 {
  114.                     FileDelimiter = "|";
  115.                 }
  116.  
  117.                 SqlConnection myADONETConnection = new SqlConnection();
  118.                 myADONETConnection = (SqlConnection)
  119.                 (Dts.Connections["DB_Conn_Soarian"].AcquireConnection(Dts.Transaction) as SqlConnection);
  120.  
  121.  
  122.                 //Reading file names one by one
  123.                 string[] fileEntries = Directory.GetFiles(SourceFolder, "*" + FileExtension);
  124.  
  125.                 foreach (string fileName in fileEntries)
  126.                 {
  127.  
  128.                     //Writing Data of File Into Table
  129.                     string TableName = "";
  130.                     int counter = 0;
  131.                     string line;
  132.                     string ColumnList = "";
  133.                     //MessageBox.Show(fileName);
  134.  
  135.                     System.IO.StreamReader SourceFile =
  136.                     new System.IO.StreamReader(fileName);
  137.                     while ((line = SourceFile.ReadLine()) != null)
  138.                     {
  139.                         if (counter == 0)
  140.                         {
  141.                             ColumnList = "[" + line.Replace(FileDelimiter, "],[") + "]";
  142.                             TableName = (((fileName.Replace(SourceFolder, "")).Replace(FileExtension, "")).Replace("\\", ""));
  143.                             string CreateTableStatement = "IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[" + SchemaName + "].";
  144.                             CreateTableStatement += "[" + TableName + "]')";
  145.                             CreateTableStatement += " AND type in (N'U'))DROP TABLE [" + SchemaName + "].";
  146.                             CreateTableStatement += "[" + TableName + "]  Create Table " + SchemaName + ".[" + TableName + "]";
  147.                             CreateTableStatement += "([" + line.Replace(FileDelimiter, "] " + ColumnsDataTypes + ",[") + "] " + ColumnsDataTypes + ")";
  148.                             SqlCommand CreateTableCmd = new SqlCommand(CreateTableStatement, myADONETConnection);
  149.                             CreateTableCmd.ExecuteNonQuery();
  150.  
  151.                             MessageBox.Show(CreateTableStatement);
  152.  
  153.                         }
  154.                         else
  155.                         {
  156.                             string query = "Insert into " + SchemaName + ".[" + TableName + "] (" + ColumnList + ") ";
  157.                             query += "VALUES('" + line.Replace(FileDelimiter, "','") + "')";
  158.  
  159.  
  160.                             //MessageBox.Show(query.ToString());
  161.                             SqlCommand myCommand1 = new SqlCommand(query, myADONETConnection);
  162.                             myCommand1.ExecuteNonQuery();
  163.                         }
  164.  
  165.                         counter++;
  166.                     }
  167.  
  168.                     SourceFile.Close();
  169.                     //move the file to archive folder after adding datetime to it
  170.                     File.Move(fileName, ArchiveFolder + "\\" + (fileName.Replace(SourceFolder, "")).Replace(FileExtension, "") + "_" + datetime + FileExtension);
  171.                     Dts.TaskResult = (int)ScriptResults.Success;
  172.                 }
  173.             }
  174.             catch (Exception exception)
  175.             {
  176.                 // Create Log File for Errors
  177.                 using (StreamWriter sw = File.CreateText(Dts.Variables["User::LogFolder"].Value.ToString()
  178.                                     + "\\" + "ErrorLog_" + datetime + ".log"))
  179.                 {
  180.                     sw.WriteLine(exception.ToString());
  181.                     Dts.TaskResult = (int)ScriptResults.Failure;
  182.                 }
  183.  
  184.             }
  185.  
  186.         }
  187.  
  188.         private string GetTextFromSomewhere()
  189.         {
  190.             throw new NotImplementedException();
  191.         }
  192.  
  193.         #region ScriptResults declaration
  194.         /// <summary>
  195.         /// This enum provides a convenient shorthand within the scope of this class for setting the
  196.         /// result of the script.
  197.         /// 
  198.         /// This code was generated automatically.
  199.         /// </summary>
  200.         enum ScriptResults
  201.         {
  202.             Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
  203.             Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
  204.         };
  205.         #endregion
  206.  
  207.     }
  208. }
  209.  
  210. When I run this i am getting an error(below)
  211. System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near '2012'.
  212. Unclosed quotation mark after the character string ')'.
  213.    at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
  214.    at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
  215.    at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
  216.    at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
  217.    at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
  218.    at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
  219.    at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
  220.    at ST_41636843287142e79bcaa204deb7adb0.ScriptMain.Main()
  221. ClientConnectionId:691d2a56-a1d3-4223-8c4f-ed95d0390bc5
  222. Error Number:102,State:1,Class:15
  223.  
  224. In the Pipe delimited file there is a column that have |'| and i want to replace it with double quotes.
Jul 26 '18 #1
1 3014
zmbd
5,501 Expert Mod 4TB
harshpatel1288
Are asking a question or just posting code?
Bytes.com isn't a "code repository" there are plenty of other sites that are code repositories and I have used them quite often when needing a novel way to solve a problem - perhaps your code is better suited to one of those sites?
Jul 28 '18 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

12
by: Joshua Beall | last post by:
Hi All, I have heard other people say that PHP can parse double quoted strings (e.g., "Hello, World") faster than it can parse single quoted strings (e.g., 'Hello, World'). This seems backwards...
2
by: Diarmaid McGleenan | last post by:
Hi all. This isn't quite the same single/double-quote problem we see posted a multitude of times in this ng. Read on... I have a js function called ShowActiveLink which accepts a string...
1
by: davegraham_1998 | last post by:
Hi All- I'm pretty sure this have been discussed earlier, but couldn't find a solution to my problem. <input type="submit" value="Delete Parts" onclick="return handleDeleteParts('ABC', 'MY...
1
by: Yannick Turgeon | last post by:
Hello all, I'm using A97. Say I've got a table "myTable" with two fields: "PK" and "Description" Say my table has three rows: PK Description 1 Elvis "The King" Presley
7
by: gar | last post by:
Hi, I need to replace all the double quotes (") in a textbox with single quotes ('). I used this code text= Replace(text, """", "'" This works fine (for normal double quotes).The problem...
2
by: MrBiggles | last post by:
Here's something I've been wondering. Do most of you use single or double quotes as a string encapsultor? ex: $s = "This is a string, I can embed ' with no prob"; vs. $s = 'This is a string, I...
7
by: nick.bonadies | last post by:
I'm trying to deal with user inputs of single quotes into form fields that get input into a MSSQL database. So far I have discovered that if I turn on magic_quotes_sybase in my php.ini file PHP...
15
by: bill | last post by:
I am trying to write clean code but keep having trouble deciding when to quote an array index and when not to. sometimes when I quote an array index inside of double quotes I get an error about...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.