Finding what value was inserted into an auto-incrementing field - sql

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.

Related

Inserting data into several tables via stored procedure

I got a performance issue with an import task (user need to import new data into the system) and could use little help.
The data within the database looks like this:
Table Categories:
Columns:
Id int primary key identity(1,1)
Code nvarchar(20) not null
RootId int not null
ParentId int not null
Table CategoryNames:
Columns:
CategoryId int not null foreign key references Category (Id)
LanguageId int not null foreign key references Language (Id)
Name nvarchar(100)
Currently it's working like this: for each row
Create connection to database
Call stored procedure with data[i]
Close connection
I already got rid of the creating and closing connection for each row of data. But it's still not good enough.
Currently the task needs round about 36 minutes to insert ~22000 categories.
The stored procedure looks like this:
procedure Category_Insert
(#code nvarchar(20),
#root int,
#parent int,
#languageId int,
#name nvarchar(100),
#id int output)
as
set nocount on
insert into Categories (Code, RootId, ParentId)
values (#code, #root, #parent)
select id = scope_identity()
insert into CategoryNames (CategoryId, LanguageId, Name)
values (#id, #languageId, #name)
Got any advice how I can speed up the performance of that task?
I would love to use bulk insert or something like that, but how would I realize the logic of the stored procedure with bulk insert?
Or is the any other way to speed this up?

Trigger to update another table WITH auto-increment value

I'm having trouble creating a trigger for my database.
I Have two tables, lets call them A and AHistory.
A has an ID and a value.
I want AHistory to keep track of the value and date for a set time.
AHistory Has an Auto Incremented ID, the value and a timestamp.
this is as far as I have gotten:
CREATE TRIGGER Atrigger
ON A
AFTER INSERT
AS
BEGIN
INSERT INTO AHistory
SELECT value FROM INSERTED
END
GO
Assuming that your db schema looks like
CREATE TABLE a
(id int identity primary key,
value varchar(32));
CREATE TABLE ahistory
(id int identity primary key,
aid int, value varchar(32),
eventdate datetime);
Your trigger might look like
CREATE TRIGGER atrigger ON A
AFTER INSERT AS
INSERT INTO ahistory (aid, value, eventdate)
SELECT id, value, GETDATE() FROM INSERTED;
Here is SQLFddle demo

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.

Foreign Key is null when insert using Stored Procedure

I've created a insert stored procedure with two tables like in the exapmle:
Table NameAge
CREATE TABLE [dbo].[Assignment3_NameAge]
(
userID int PRIMARY KEY IDENTITY(1,1),
Name varchar(255) NOT NULL,
Age int NOT NULL
)
Table Hobbies
CREATE TABLE [dbo].[Assignment3_Hobbies]
(
hobbiesID int Identity(1,1) Primary Key,
userID int Foreign Key references Assignment3_NameAge(userID),
hobbies varchar(255) NOT NULL,
)
Insert Stored Procedure
CREATE PROCEDURE [dbo].p_Assignment3Join_ins
#Name nvarchar(100),
#Age int,
#Hobbies nvarchar(100)
AS
INSERT INTO [TABLE].[dbo].[Assignment3_NameAge]
([Name]
,[Age])
VALUES (#Name,#Age)
INSERT INTO [TABLE].[dbo].[Assignment3_Hobbies]
([Hobbies])
VALUES (#Hobbies)
The problem is that when i run the stored procedure the table Hobbies has a null value for userid(the foreign key)
What am i doing wrong?
You should provide the key of the Assignment3_NameAge value you want to insert into Assignment3_Hobbies.
If you want the last inserted you can use SCOPE_IDENTITY() from SQL Server(if you're using SQL Server) or equivalent. It will give you the last inserted value from Assignment3_NameAge
I am guessing this is SQL Server based on the IDENTITY column. Correct?
The first insert creates a user, but there is no user ID being set on the insert of the hobby. You need to capture the identity value from the first insert to be used in the second insert. Have you gon over the system functions available?
You're not supplying a value for it, SQL won't automagically fill the value in for you even though you've created a Foreign Key relationship. It's your job to populate the tables.

SQL INSERT stored procedure not working

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, ...)