简体   繁体   中英

Error, when inserting into sql from C# code behind

I am trying to insert some new threat into two tables at the same time. The sql statement when running within sql management studio, works like a charm. But when i try and do an aspx page, coding the sql statement in C# codebehind, it returns something like it can not insert empty. I have tried different sql statements, yet nothing seems to work.

The original statements are as following:

DECLARE @BrugerNavn NVARCHAR(50) = 'Bent'
DECLARE @Besked NVARCHAR(MAX) = 'Bents besked'
DECLARE @TraadNavn NVARCHAR(50) = 'Bents tråd'
DECLARE @KategoriID INT = 1

INSERT INTO TraadTabel
VALUES (@TraadNavn, @KategoriID)

INSERT INTO Beskeder
VALUES (@Besked, SCOPE_IDENTITY(), @BrugerNavn)

My C# code is as following:

protected void btnSubmit_Click(object sender, EventArgs e)
{
    string BrugerNavn = txtBrugerNavn.Text;
    string TradNavn = txtTraadNavn.Text;
    string Besked = txtBesked.Text;
    int KategoriID = int.Parse(Request.QueryString["id"]);

    SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["SimpeltForumConnectionString"].ConnectionString);
    SqlCommand FirstLoad = new SqlCommand("INSERT INTO TraadTabel VALUES (@TradNavn, @KategoriID)", conn);
    //SqlCommand SecondLoad = new SqlCommand("INSERT INTO Beskeder VALUES (@Besked, SCOPE_IDENTITY(), @BrugerNavn)", conn);
    SqlCommand SecondLoad = new SqlCommand("INSERT INTO Beskeder VALUES (@Besked, SELECT IDENT_CURRENT(IndlaegID)+1, @BrugerNavn)", conn);

    FirstLoad.CommandType = CommandType.Text;
    FirstLoad.Parameters.AddWithValue("@TradNavn", TradNavn);
    FirstLoad.Parameters.AddWithValue("@KategoriID", KategoriID);
    SecondLoad.Parameters.AddWithValue("@Besked", Besked);
    SecondLoad.Parameters.AddWithValue("@BrugerNavn", BrugerNavn);

    using (conn)
    {
        conn.Open();
        FirstLoad.ExecuteNonQuery();
        SecondLoad.ExecuteNonQuery();
    }
}

As you can see, I have commented the "SCOPE_IDENTITY()"-line out, and left it, as it is the code that actually works, when triggered from within sql management studio. And I think that it is the scope identity, that returns the error in my browser. I do not know what to do, please help. Thanks.

Instead of:

 SqlCommand FirstLoad = new SqlCommand("INSERT INTO TraadTabel VALUES (@TradNavn, @KategoriID)", conn);
 SqlCommand SecondLoad = new SqlCommand("INSERT INTO Beskeder VALUES (@Besked, SELECT IDENT_CURRENT(IndlaegID)+1, @BrugerNavn)", conn); 

make them as one command, like this:

    SqlCommand MyOnlyLoad = new SqlCommand("INSERT INTO TraadTabel VALUES (@TradNavn, @KategoriID) GO INSERT INTO Beskeder VALUES (@Besked, SELECT IDENT_CURRENT(IndlaegID)+1, @BrugerNavn) ", conn);

Then handle the rest of code as one command.

Hope, it will be work.

SCOPE_IDENTITY is the autogenerated ID value of the last inserted record. So you don't need to pass it to the insert command. You can retrieve it in ADO.NET and use it as parameter for your next command. You can use SELECT CAST(scope_identity() AS int) :

using (var con = new SqlConnection(WebConfigurationManager.ConnectionStrings["SimpeltForumConnectionString"].ConnectionString)) {
    con.Open();
    int newID;
    var sql = "INSERT INTO TraadTabel VALUES (@TradNavn, @KategoriID);SELECT CAST(scope_identity() AS int);";
    using (var insertCommand1 = new SqlCommand(sql, con)) {
        insertCommand1.Parameters.AddWithValue("@TradNavn", TradNavn);
        insertCommand1.Parameters.AddWithValue("@KategoriID", KategoriID);
        newID = (int)insertCommand1.ExecuteScalar();
    }
    sql = "INSERT INTO Beskeder VALUES (@Besked, @newID, @BrugerNavn);";
    using (var insertCommand2 = new SqlCommand(sql, con)) {
        insertCommand2.Parameters.AddWithValue("@newID", newID);
        insertCommand2.Parameters.AddWithValue("@Besked", Besked);
        insertCommand2.Parameters.AddWithValue("@BrugerNavn", BrugerNavn);
        var affectedRecords = insertCommand2.ExecuteNonQuery();
    }
}

i would recommend you to use stored procedure instead. it will also be easier to handle them later. and you would be able to use your original statements as they are. stored procedure would be like:

CREATE PROCEDURE Insert_TraadTabel_AND_Beskeder                    
 -- Add the parameters for the stored procedure here                          
 DECLARE @BrugerNavn NVARCHAR(50), 
DECLARE @Besked NVARCHAR(MAX),
DECLARE @TraadNavn NVARCHAR(50),
DECLARE @KategoriID INT         

AS                            
BEGIN                            
 -- SET NOCOUNT ON added to prevent extra result sets from                            
 -- interfering with SELECT statements.                            
 SET NOCOUNT ON; 

INSERT INTO TraadTabel
VALUES (@TraadNavn, @KategoriID)

INSERT INTO Beskeder
VALUES (@Besked, SCOPE_IDENTITY(), @BrugerNavn) 
END

code would be something like this:

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        using (conn)
        {
            SqlCommand command;
            command = new SqlCommand();
            command.Connection = conn;
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "Insert_TraadTabel_AND_Beskeder";
            command.Parameters.Add("@TradNavn", SqlDbType.NVarChar).Value = txtTraadNavn.Text;
            command.Parameters.Add("@KategoriID", SqlDbType.Int).Value = int.Parse(Request.QueryString["id"]);
            command.Parameters.Add("@Besked", SqlDbType.NVarChar).Value = txtBesked.Text;
            command.Parameters.Add("@BrugerNavn", SqlDbType.NVarChar).Value = txtBrugerNavn.Text;
            command.ExecuteNonQuery();
        }
    }

Thanks all.... I have tried different approaches. Nothing seems to work for me. I have decided to try and do the code all over again. Starting from scratch. Sometimes it works. Some times it does not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM