SQL INSERT stored procedure not working - sql

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.

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

You need to specify which value goes to which field.
INSERT INTO Anuncio (field1, field2, ...) VALUES (#Titulo, ...)

Related

Specify "NEXT VALUE" for INSERT statement using identity column in SQL Server

Consider the following table and SQL from Microsoft's INSERT documentation that deals with IDENTITY columns:
CREATE TABLE dbo.T1 (column_1 int IDENTITY, column_2 VARCHAR(30));
GO
INSERT T1 (column_2) VALUES ('Row #2');
The INSERT statement does not specify column_1 as a column of the table, and SQL Server auto-populates the next value for that identity column. This is the normal way identity columns are handled.
How can I have the same behavior, while also specifying the column name?
For example, I'm looking for something like:
INSERT INTO T1 (column_1, column_2)
VALUES (NEXT VALUE, 'Row #3');
GO
I don't believe NEXT VALUE works here, but is there something that does work? Is there a key token or function that will indicate that the identity column should be used?
Note: the reason I ask is that the framework I'm using requires all columns to be specified in the column list.
If you are on SQL Server 2012 and later, you can use sequence. But you must remove the IDENTITY property from Column1 first. This can only be done by copy-and-rename a new table.
CREATE SEQUENCE Column1_Sequence
AS int
START WITH 0;
CREATE TABLE T1
(
Column1 int DEFAULT (NEXT VALUE FOR Column1_Sequence) PRIMARY KEY
, Column2 nvarchar(30)
)
After that, you can insert data into the table in 2 ways:
INSERT INTO T1 (Column1, Column2)
SELECT NEXT VALUE FOR Column1_Sequence
, 'Row #2'
INSERT INTO T1 (Column2)
SELECT 'Hello world'
Can you set the identity insert on before inserting and then set the identity insert off
You cannot set value for identity column unless you set identity_insert on for this table (one at time). Some examples:
create table #tmp (id int identity(1,1), name varchar(10))
insert #tmp (id,name) values (2,'test')
--error Cannot insert explicit value for identity column in table '#tmp
set identity_insert #tmp on --for one table in DB
insert #tmp (id,name) values (2,'qwas')
select * from #tmp
set identity_insert #tmp off -- good practice
--works
--see current identity value
SELECT IDENT_CURRENT ('#tmp') AS Current_Identity;
--Reset identity value
DBCC CHECKIDENT (#tmp, RESEED, 999)
--next insert will be 1000
Of course, if you reset next identity to a value which conflicts with PK (common usage of identity) you will have Violation of PRIMARY KEY constraint error
I am pretty sure there is no way to do that with SQL Server. Two workarounds that I can think of:
Fix the library if possible.
If the library supports it, you can create a view and INSERT into that instead. For example:
CREATE TABLE MyTable
(
ID INT IDENTITY(1, 1),
SomeColumn VARCHAR(100)
)
GO
CREATE VIEW MyTableView
AS
SELECT SomeColumn
FROM MyTable
GO
INSERT INTO MyTableView (SomeColumn) VALUES ('Test')

Finding what value was inserted into an auto-incrementing field

I have two tables:
Rooms:
ID (auto-incrementing primary key, int)
Topic (varchar(50))
MangerId (varchar(50))
Rooms_Users:
UserId (varchar(50))
RoomId (varchar(50))
both fields together are the primary key
I want to insert a room but I also must insert the manger to the table rooms_users.
Here is what I have so far:
ALTER PROCEDURE [dbo].[Creat_Room] #MangerId varchar(50) ,#Topic varchar(50)
AS
BEGIN
SET NOCOUNT
insert into Rooms(ManagerId,Topic) values(#MangerId,#Topic)
insert into Rooms_Users(UserId,RoomId) values(#MangerId,?????????????)
END
The ????????????? is the problem: I don't know what to put here i want to put the roomid i insert above.
You can use the output clause. Look at MSDN here: OUTPUT Clause (Transact-SQL)
Example:
declare #tbl table
(
NewID int
)
insert into Rooms(ManagerId,Topic)
output inserted.ID into #tbl
values(#MangerId,#Topic)
Then the table variable will contains the new id given to the row you inserted
Use the SCOPE_IDENTITY() function:
ALTER PROCEDURE [dbo].[Create_Room]
#ManagerId varchar(50),
#Topic varchar(50)
AS
BEGIN
DECLARE #NewRoomID INT
insert into Rooms(ManagerId, Topic) values(#MangerId, #Topic)
SELECT #NewRoomID = SCOPE_IDENTITY()
insert into Rooms_Users(UserId, RoomId) values(#ManagerId, #NewRoomID)
END
This function will return the last inserted IDENTITY value in this particular scope - the scope of your stored procedure.

update two tables with one Store Procedure in SQL server?

I have problem when I tried to update two tables in one Store Procedure I get the SqlException could some one help me
The INSERT statement conflicted with the FOREIGN KEY constraint "FK".
The conflict occurred in database "", table "dbo.Users", column
'userID'. The statement has been terminated.
ALTER PROCEDURE [dbo].[CreateProject]
#ProjectID UNIQUEIDENTIFIER,
#UserID UNIQUEIDENTIFIER,
#ProjectName NVARCHAR(50),
#Description NTEXT,
#EstStartDate DATETIME,
#EstEndDate DATETIME,
#StatusID SMALLINT,
#Priority SMALLINT
AS
INSERT INTO DBO.Projects VALUES
(#ProjectID,#ProjectName,GETDATE(),#Description,#EstStartDate,#EstEndDate,#StatusID,#Priority)
INSERT INTO Users_projects VALUES
(#ProjectID,#UserID)
Problem is with the Foreign Key of UserID. You need to insert UserId into the Users table first. Few pointers: "createProc" procedure generally should create the ProjectId and return as an OUTPUT parameter. Also, you may want to use username as input parameter and let the proc look up the UserId.

SQL Server 2005: T-SQL INSERT INTO and OUTPUT timestamp to a variable

Example:
IF OBJECT_ID('T1') IS NOT NULL
DROP TABLE T1;
GO
CREATE TABLE T1 (id int PRIMARY KEY, timestamp);
GO
INSERT INTO T1(id) VALUES (1);
GO
declare #v timestamp;
INSERT INTO T1(id) OUTPUT inserted.timestamp as v VALUES (10);
select #v
How can I get the inserted.timestamp into variable #v?
This is what I got to work:
IF OBJECT_ID('T1') IS NOT NULL
DROP TABLE T1;
GO
CREATE TABLE T1 (id int PRIMARY KEY, timestamp);
GO
INSERT INTO T1(id) VALUES (1);
GO
declare #v as table ([timestamp] varbinary) --timestamp;
INSERT INTO T1(id)
OUTPUT inserted.[timestamp] into #v
VALUES (10);
select * from #v
One thing you need to realize is a timestamp field cannot be manually populated. So you must use some other type in your output table. ANd BTW timestamp is deprecated, I would not use it in new development at all. Use rowversion instead. And timestamp doesn't mean it will be a date for those who think it should be like the ANSII Standard, IN SQL Server it is not a date or convertable to a date.
One way would be to use identity:
declare #v timestamp;
declare #ID int;
INSERT INTO T1(id) OUTPUT inserted.timestamp as v VALUES (10);
select #ID =##IDENTITY;
select #v=timestamp from T1 where id=#ID;
(edit)... of course that would require an identity column. Since you know the value of the ID you are inserting then you don't even need to do this, just select the same row after you insert it using your original value.
Is the point you would like to do this all in a single statement? You could probably do it with a trigger but seems unnecessary.
Well, you're inserting a specific value into the ID column, which is the primary key - so just read out the row once you've inserted it...
INSERT INTO T1(id) VALUES (1);
GO
DECLARE #v timestamp
SELECT #v = TIMESTAMP
FROM dbo.T1
WHERE ID = 1
SELECT #v

how to enter values in rowguid column?

can anyone please tell me the right way to insert values in the rowguid column of the table? I m using sql server management studio
use the NEWID() function to generate one:
CREATE TABLE myTable(GuidCol uniqueidentifier
,NumCol int)
INSERT INTO myTable Values(NEWID(), 4)
SELECT * FROM myTable
or you can set it as a default value:
CREATE TABLE myTable(GuidCol uniqueidentifier DEFAULT NEWSEQUENTIALID()
,NumCol int)
INSERT INTO myTable (NumCol) Values(4)
SELECT * FROM myTable
You can Set NEWSEQUENTIALID() as Default in table
CREATE TABLE GuidTable
(
ID UNIQUEIDENTIFIER DEFAULT NEWSEQUENTIALID() PRIMARY KEY,
TEST INT
)
Read more about it here
http://msdn.microsoft.com/en-us/library/ms189786.aspx
It's a uniqueidentifier column
You can send a value like "6F9619FF-8B86-D011-B42D-00C04FC964FF", or use NEWID/NEWSEQUENTIALID functions to generate one
I was able to insert by using the following:
Insert Into Table FOO(Col1, Col2, RowGuidCol)
Values (5,'Hello,'1A49243F-1B57-5848-AA62-E4704544BB34')
It is very important to follow to place the dashes in the correct place. You do not need to have the 0x in the beginning of the string. FYI-Updates are not allow on columns whith the rowguid col property set. I hope this helps.
Assuming that you have a uniqueidentifier column rg in your table t which is set to be the rowguid:
INSERT INTO TABLE t (rg) VALUES (NEWID())
or
INSERT INTO TABLE t (rg) VALUES (NEWSEQUENTIALID())