Pregunta

SQL insert issue. Running a stored procedure to insert rows to a table and returning the ID created. WHen I run it like this and have an output parameter @ID and use ExecuteNonQuery() it returns -1 for my int idinserted but does give me back the ID inserted. SHouldn't it return 1 since the record was inserted. I'd like to use ExecuteNonQuery to check the record was inserted then grab the inserted ID.

SQL INSERT

@person bigint,
@date datetime,
@ID bigint OUTPUT

AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO table(person,DATE_ADDED)
    VALUES (@person,@date)

    SELECT @ID = SCOPE_IDENTITY()
    cmd.Parameters.Clear();
    cmd.Parameters.AddWithValue("@person", person);
    cmd.Parameters.AddWithValue("@date", DateTime.Now);

    SqlParameter output = new SqlParameter("@ID", SqlDbType.Int);
    output.Direction = ParameterDirection.Output;

    cmd.Parameters.Add(output);
    int idinserted = (int)cmd.ExecuteNonQuery();
    if (idinserted > 0)
    {
        int ID = output.Value;
    }

When I do the insert and c# like this with ExecuteScalar()

SQL INSERT

@person bigint,
@date datetime
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO table(person ,DATE_ADDED)
    VALUES(@person,@date )

    SELECT SCOPE_IDENTITY()

    cmd.Parameters.Clear();
    cmd.Parameters.AddWithValue("@person", person);
    cmd.Parameters.AddWithValue("@date", DateTime.Now);
    long ID = (long)cmd.ExecuteNonScalar();

ExecuteScalar() throws the following error

"Specificed Cast it not valid

¿Fue útil?

Solución

Remove

SET NOCOUNT ON;

Because that removes the rowcount!

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top