tags:

views:

273

answers:

2
Create Proc CrearNuevoAnuncio
    @Titulo varchar(250),
    @Precio int,
    @Descripcion varchar(250),
    @IDCategoria int,
    @IDImagen int, 
    @Login varchar(200)

AS

INSERT INTO Anuncio VALUES(
    @Titulo,
    @Precio,
    @Descripcion,
    @IDCategoria,
    @IDImagen, 
    @Login
    )

The error is because the table anuncio has 1 more attribute: "idAnuncio". It's the primary key, and it's the indentity (autoincrement).

So, how can I handle this is the missing thing is an Identity. I don't want to pass that parameter from my front-end.

+8  A: 

You need to specify which value goes to which field.

INSERT INTO Anuncio (field1, field2, ...) VALUES (@Titulo, ...)
Zed
+8  A: 

You need to specify the explicit list of columns in your insert statement:

INSERT INTO 
   Anuncio(Titulo, Precio, Descripcion, IDCategoria, IDImagen, Login)
VALUES
   (@Titulo, @Precio, @Descripcion, @IDCategoria, @IDImagen,  @Login)

Otherwise, SQL Server will try to insert values for ALL columns which fails here. It cannot insert a value into an IDENTITY column - that column will be set automatically by SQL Server upon inserting a new row, and is guaranteed to be unique.

Is the ID field of type "INT IDENTITY" ? In that case, you could access the value of the newly inserted ID like this:

 DECLARE @NewID INT
 SET @NewID = SCOPE_IDENTITY()

and possibly return it from the stored proc:

 RETURN @NewID

Marc

marc_s
+1 for complete insert example using OP's code
free-dom
Not really answered my question. I want to insert a new record, but IdAnuncio is an IDENTITY which autoincrements whenever there is a new record. How can I create a stored procedure taking this into account?
Sergio Tapia
Ok, I modified my code using your example above, and the procedure executed correctly (it got created), so I take it that my PrimaryKey(identity-type) will autoincrement regardless if it's not mentioned even once in my stored procedure?
Sergio Tapia
Yes, an "IDENTITY" field will be automatically handled by the database - that's the whole point of having an IDENTITY
marc_s
All I needed to know. :3 Thanks!
Sergio Tapia