Hi, folks.
I’m creating an application in C# with Visual Studio which works with SQLSERVER. I created a routine to write data in the DB, which inserts data in 2 tables. In the first one it’s working fine, but the second always gives an error with the message: “code 102: incorrect syntax next to ‘(‘”.
I’ve executed step by step and the syntax seems to be correct. I changed the way the command is composed, but the error persists. The change is a commented piece of code The code of the routine is as follows.
- public static bool GravaRegistroDuplo(string StabelaPri, List<string> ScamposPri, List<string> StiposPri, List<string> SdadosPri, string StabelaSec,
- List<string> ScamposSec, List<string> StiposSec, List<string> SdadosSec, ref string Smensagem)
- {
- string TextoSQL = "insert into " + StabelaPri + "(";
- int i;
-
- for (i = 0; i < ScamposPri.Count; i++)
- TextoSQL += ScamposPri[i] + ",";
- TextoSQL = TextoSQL.Substring(0, TextoSQL.Length - 1) + ")";
-
- TextoSQL += " values(";
- for (i = 0; i < SdadosPri.Count; i++)
- TextoSQL += "@Val" + i + ",";
- TextoSQL = TextoSQL.Substring(0, TextoSQL.Length - 1) + ")";
- using (var con = new SqlConnection(ConfigurationManager.AppSettings["TextoConexao"]))
- {
- con.Open();
-
- SqlTransaction Tran = con.BeginTransaction();
- try
- {
- string nome;
- SqlCommand Cmd = new SqlCommand(TextoSQL, con, Tran);
-
- for (i = 0; i < SdadosPri.Count; i++)
- {
- nome = "@Val" + i.ToString();
- if (StiposPri[i] == "numeric")
- Cmd.Parameters.AddWithValue(nome, float.Parse(SdadosPri[i]));
- else
- Cmd.Parameters.AddWithValue(nome, SdadosPri[i]);
- }
- TextoSQL = TextoSQL.Substring(0, TextoSQL.Length - 1) + ")";
- Cmd.ExecuteNonQuery();
-
- Cmd.Dispose();
- TextoSQL = "select @@identity";
- Cmd = new SqlCommand(TextoSQL, con, Tran);
- SqlDataReader rdr;
- rdr = Cmd.ExecuteReader();
-
- if (rdr.Read())
- {
- if (rdr.GetValue(0).ToString() != "")
- SdadosSec[0] = rdr.GetValue(0).ToString();
- }
- rdr.Close();
-
- Cmd.Dispose();
- TextoSQL = "insert into " + StabelaSec + "(";
- Cmd = new SqlCommand(TextoSQL, con, Tran);
- for (i = 0; i < ScamposSec.Count; i++)
- TextoSQL += ScamposSec[i] + ",";
- TextoSQL = TextoSQL.Substring(0, TextoSQL.Length - 1) + ")";
-
- TextoSQL += " values(";
- for (i = 0; i < ScamposSec.Count; i++)
- {
- if (StiposSec[i] == "integer")
- TextoSQL += SdadosSec[i] + ",";
- else if (StiposSec[i] == "numeric")
- TextoSQL += SdadosSec[i] + ",";
- else if (StiposSec[i] == "string")
- TextoSQL += "'" + SdadosSec[i] + "',";
- else if (StiposSec[i] == "date")
- TextoSQL += "'" + SdadosSec[i] + "',";
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- TextoSQL = TextoSQL.Substring(0, TextoSQL.Length - 1) + ")";
- Cmd.ExecuteNonQuery();
-
- Tran.Commit();
- Smensagem = "Sucesso";
- return true;
- }
- catch (SqlException ex)
- {
- Tran.Rollback();
- Smensagem = "Código: " + ex.Number + "\nMensagem: " + ex.Message;
- return false;
- }
- }
- }
Can anybody help me? Thanks a lot.