Y
Y
Yes2019-08-15 04:07:20
C++ / C#
Yes, 2019-08-15 04:07:20

Why is the stored procedure not executed when called from C# (only works from SQL)?

There is such a table:

CREATE TABLE [dbo].[DataAdditional] (
    [Id]              INT            IDENTITY (1, 1) NOT NULL,
    [Alpha]        INT            NULL,
    [Bravo]        BIGINT      NULL,
    [Charlie]      BIGINT      NULL,
    [Delta]        INT            NULL,
    [Echo]         INT            NULL,
    [Foxtrot]     INT            NULL,
    [Golf]          INT            NULL,
    [Hotel]        NVARCHAR (MAX) NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

And this procedure:
CREATE PROCEDURE [dbo].[AddAdditionalData]
   @alpha int = 0,
   @bravo bigint = 0,
   @Charlie bigint = 0,
    @Delta int = 0,
    @Echo int = 0,
    @Foxtrot int = 0,
    @Golf int = 0,
    @Hotel nvarchar(max) = N''            	
AS
BEGIN
  INSERT INTO dbo.DataAdditional(Alpha, Bravo, Charlie, Delta, Echo, Foxtrot, Golf, Hotel)
  --VALUES (@alpha, @bravo, @Charlie, @Delta, @Echo, @Foxtrot, @Golf, @Hotel) --Не работает --
  VALUES (23651, 12587156333, 99999, 2321, 2, 21, 4, N'Значимость этих проблем настолько очевидна, что сложившаяся структура организации создаёт...                                                                                                                                                                
')
END

--exec dbo.AddAdditionalData 23651, 12587156333, 99999, 2321, 2, 21, 4, N'Значимость этих проблем настолько очевидна, что сложившаяся структура организации создаёт...                                                                                                                                                                  ' --
--вот этот exec работает
exec dbo.AddAdditionalData
-- а этот работает если раскоменчин второй VALUES, а первый закоменчен.

This is how I call the procedure from C#:
public void AddSecondData(MainWindow.DataSecond dataSecond)
        {
            //ClearData();
            using (SqlConnection con = new SqlConnection(ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand("dbo.AddAdditionalData", con))//без dbo тоже пробовал
                {
                    cmd.CommandType = CommandType.StoredProcedure;

                    cmd.Parameters.Add("@alpha", SqlDbType.Int).Value = dataSecond.Alpha;
                    cmd.Parameters.Add("@bravo", SqlDbType.BigInt).Value = Convert.ToInt64(dataSecond.Bravo);
                    cmd.Parameters.Add("@Charlie", SqlDbType.BigInt).Value = Convert.ToInt64(dataSecond.Charlie);
                    cmd.Parameters.Add("@Delta", SqlDbType.Int).Value = dataSecond.Delta;
                    cmd.Parameters.Add("@Echo", SqlDbType.Int).Value = dataSecond.Echo;
                    cmd.Parameters.Add("@Foxtrot", SqlDbType.Int).Value = dataSecond.Foxtrot;
                    cmd.Parameters.Add("@Golf", SqlDbType.Int).Value = dataSecond.Golf;
                    cmd.Parameters.Add("@Hotel", SqlDbType.NVarChar).Value = dataSecond.Hotel;

                    if (cmd.Connection.State == ConnectionState.Closed)
                    {
                        cmd.Connection.Open();
                    }
                    cmd.ExecuteNonQuery();
                    // пробовал завернуть в try catch, но никаких exception не получил.
                }
            }
        }

This is hardly a problem, but DataSecond looks like this

public class DataSecond
        {
            public int Alpha;
            public long Bravo;
            public long Charlie;
            public int Delta;
            public int Echo;
            public int Foxtrot;
            public int Golf;
            public string Hotel;
         }

The database was created through the context menu in VS. There is a connection, I check it before performing the procedure.
Why is that? There are no errors while executing the method. The table just doesn't populate. Even default values ​​are not set. Although the procedure from C# is definitely called.
UPD :
Most likely the problem is in C# itself. Since after calling the procedure through it, and updating the table (to see the data), I get:

This database cannot be imported. It is either an unsupported SQL server version or an unsupported database compatibility.

Googled it, it looks like this:
public void AddSecondData(MainWindow.DataSecond dataSecond)
        {
                SqlConnection connection = GetConnection();

                using (SqlCommand cmd = new SqlCommand("dbo.AddAdditionalData", con))
                    cmd.CommandType = CommandType.StoredProcedure;

                    cmd.Parameters.Add("@alpha", SqlDbType.Int).Value = dataSecond.Alpha;
                    cmd.Parameters.Add("@bravo", SqlDbType.BigInt).Value = Convert.ToInt64(dataSecond.Bravo);
                    cmd.Parameters.Add("@Charlie", SqlDbType.BigInt).Value = Convert.ToInt64(dataSecond.Charlie);
                    cmd.Parameters.Add("@Delta", SqlDbType.Int).Value = dataSecond.Delta;
                    cmd.Parameters.Add("@Echo", SqlDbType.Int).Value = dataSecond.Echo;
                    cmd.Parameters.Add("@Foxtrot", SqlDbType.Int).Value = dataSecond.Foxtrot;
                    cmd.Parameters.Add("@Golf", SqlDbType.Int).Value = dataSecond.Golf;
                    cmd.Parameters.Add("@Hotel", SqlDbType.NVarChar).Value = dataSecond.Hotel;

                    if (cmd.Connection.State == ConnectionState.Closed)
                    {
                        cmd.Connection.Open();
                    }
                    cmd.ExecuteNonQuery();
                    // пробовал завернуть в try catch, но никаких exception не получил.
                }            
        }

        private SqlConnection GetConnection()
        {
            SqlConnectionStringBuilder connectionString = new SqlConnectionStringBuilder();
            connectionString.DataSource = "(localdb)\\MSSQLLocalDB";
            connectionString.AttachDBFilename = "|DataDirectory|\\MainDB.mdf";
            connectionString.IntegratedSecurity = true;
            string connectString = connectionString.ConnectionString;

            SqlConnection connection = new SqlConnection(connectString);
            return connection;
            //return @"data source=(LocalDB)\MSSQLLocalDB;attachdbfilename=|DataDirectory|\MainDB.mdf;MultipleActiveResultSets=True;";

            //return @"Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=MainDB;"
            //    + "Integrated Security=true;";
        }

but it did not help.
UPD 2:
The problem is 100% in C#. I created a procedure that deletes everything from the table, manually added data to the table, and I also call a new procedure from C #. Nothing has been deleted and there are no errors (try catch also shows nothing).

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yes, 2019-08-16
@volkihar

I apologize for this question. The problem was not in the code. I looked at the .mdf file which is in Solution Explorer and in Server Explorer.
It turned out that there is another file, which is located in ProjectName/bin/Debug/Main.mdf.
That's where all requests go. But I didn't create it. I don’t understand how it ended up there, and why, after updating the .sql scripts in the first .mdf database, they were updated there as well.

D
Developer, 2019-08-15
@samodum

If you remove PRIMARY KEY CLUSTERED ([Id] ASC)
it it will work.

CREATE TABLE [dbo].[DataAdditional] (
    [Id]              INT            IDENTITY (1, 1) NOT NULL,
    [Alpha]        INT            NULL,
    [Bravo]        BIGINT      NULL,
    [Charlie]      BIGINT      NULL,
    [Delta]        INT            NULL,
    [Echo]         INT            NULL,
    [Foxtrot]     INT            NULL,
    [Golf]          INT            NULL,
    [Hotel]        NVARCHAR (MAX) NULL
  -- , PRIMARY KEY CLUSTERED ([Id] ASC)
);

The problem is in this line

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question