Return AutoIncremeting ID upon insert - sql

I have a stored procedure that inserts into a table that has two values, id and username. The id field is autoincremeting so my stored procedure looks like:
CREATE PROCEDURE [dbo].[sp_test]
#username varchar(50)
AS
BEGIN
INSERT INTO dbo.testtable(username)
SELECT
#username
FROM
tbl.test2
WHERE
username IS NOT NULL
How can I return the id even when there it is not explicitly stated? I attempted the SCOPE_IDENTITY(); keyword but I was receiving blanks and nulls.

Taking a guess as to what you want I think it would be something more like this.
CREATE PROCEDURE [dbo].[Insert_test]
(
#username varchar(50)
) AS
BEGIN
INSERT INTO dbo.testtable
(
username
)
VALUES
(
#username
)
select SCOPE_IDENTITY()
END

If you're really inserting several rows from a table, you can get the ids this way:
INSERT INTO dbo.testtable(username)
output inserted.id
SELECT username
FROM dbo.test2
where username is not null

Related

Delete and Insert Into

I'm looking to execute a stored procedure everyday where it will firstly delete the data within a specified table and then insert the new data in.
My stored procedure looks roughly like this
ALTER PROCEDURE [dbo].[SP_Name]
AS BEGIN
WITH CTE_Name as
( select
Title,
First_Name,
Surname
From table
)
DELETE [dbo].[NEW_TABLE]
INSERT INTO [dbo].[NEW_TABLE]
Select * from CTE_NAME
END
When I execute the query I get the error invalid object name 'CTE_NAME'
I have tried removing the 'DELETE [dbo].[NEW_TABLE]' line and upon doing this the stored procedure does run and does insert the data into the table.
I'm using SQl Management Studio 2012
I think you need to separate your With by adding a semicolon in front of it
below code should work
DECLARE #TABLE TABLE (
id VARCHAR(100)
)
DELETE FROM #TABLE
;WITH CTE_Name AS
(
SELECT id FROM OtherTable
)
INSERT INTO #TABLE
SELECT id FROM CTE_Name
You could try this code:
ALTER PROCEDURE [dbo].[SP_Name] AS
BEGIN
DECLARE #helperTbl TABLE (Title varchar(100), First_Name varchar(100), Surname varchar(100))
INSERT INTO #helperTbl
SELECT Title,
First_Name,
Surname
FROM [table]
DELETE FROM [dbo].[NEW_TABLE]
INSERT INTO [dbo].[NEW_TABLE]
SELECT * FROM #helperTbl
END

Return inserted row from stored procedure

I have the following stored procedure
CREATE PROCEDURE [dbo].[spInsert]
#name nvarchar(128),
AS
insert into NameIdentifier
( Name, Identifier)
values
( #name, NEWID());
SELECT #new_identity = SCOPE_IDENTITY()
SELECT * FROM NameAge where Id = #new_identity
Is there are a more efficient way to return the last inserted record complete with id and associated data?
Use Insertedwithin output clause,
As the follwoing:
CREATE PROCEDURE [dbo].[spInsert]
#name nvarchar(128),
AS
DECLARE #MyTableVar table(
Name varchar(50),
Identifier uniqueidentifier
;
insert into NameIdentifier
( Name, Identifier)
values
( #name, NEWID());
OUTPUT INSERTED.Name, INSERTED.Identifier
INTO #MyTableVar
SELECt Name,Identifier from #MyTableVar
Refreance:
Best way to get identity of inserted row?
SCOPE_IDENTITY() is used to get the last generated Identity value in an identity column in your scope , For GUID values either you get the guid before you insert it like I have done in the code below , or you use OUTPUT clause to get the guid generated by the Insert statement.
CREATE PROCEDURE [dbo].[spInsert]
#name nvarchar(128)
AS
BEGIN
SET NOCOUNT ON;
Declare #NewID UNIQUEIDENTIFIER = NEWID();
insert into NameIdentifier ( Name, Identifier)
values( #name, #NewID);
SELECT * FROM NameAge where Id = #NewID;
END
This should give you your desired functionality.
CREATE PROCEDURE [dbo].[spInsert]
#name nvarchar(128),
#Ret int Output
AS
BEGIN
insert into NameIdentifier
( Name, Identifier)
values
( #name, NEWID());
END
SET #Ret = ##IDENTITY
EDIT: This will return the id of your newly inserted row.
You can achieve this by using the output clause of SQL Server, you can read more about this here
if exists (select 1 from sys.tables where name = 'NameIdentifier ')
drop table NameIdentifier
create table NameIdentifier
(
id BIGINT IDENTITY(1,1)
,Name VARCHAR(100)
,Identifier uniqueidentifier
)
DECLARE #id TABLE
(
ID BIGINT
)
INSERT INTO NameIdentifier (Name,Identifier)
OUTPUT INSERTED.id INTO #id
VALUES('abcd',NEWID())
SELECT * FROM NameIdentifier N, #id I where N.id = I.id

while loop to get two variables to stored procedure

I want to write a stored procedure to loop through the table which has membership id and person id details and pass it as variable to stored procedure.
Any thoughts on how to do it. Any help is highly appreciated.
DECLARE #membership NUMERIC(9)
DECLARE #person_id NUMERIC(9)
DECLARE #id_num INT
WHILE (
set #id_num=id_num+1
SELECT membership_id,person_id FROM [dbo].[reb] WHERE id_num <1160
EXEC p_get_details #membership_id, person_id
You have two options. first one is to pass two parameters to procedure p_get_details , each parameter being a comma separated string containing concatenated values of membership_id and person_id columns.
Other is to pass the whole resultset from SELECT query as a Table Valued Parameter to the procedure.
If you need to call the proc again and again for different table values then u can create a temp table which has all the membership and personids
See If this code works for you:-
DECLARE #membership_id NUMERIC(9)
DECLARE #person_id NUMERIC(9)
if(OBJECT_ID('tempdb..#tempids') is not null)
drop table #tempids
SELECT membership_id,person_id
into #tempids
FROM [dbo].[reb]
WHERE id_num <1160
while exists(select 1 from #tempids)
begin
-- select 1 row which will be called by proc
select top 1 #membership_id=membership_id
#person_id =person_id
from #tempids
EXEC p_get_details #membership_id, #person_id
--delete the ids which have been called by proc
delete from #tempids
where
membership_id=#membership_id
person_id =#person_id
end

Insert data on a table from stored procedure resultset

I have a stored procedure that gets data from different tables. I want a few fields from the result set of the stored procedure to be inserted on another table.
How can I do this? Cursor, another stored procedure or what?
You can insert the result set from a stored procedure into another table, as in this example from this article:
DECLARE #People TABLE
(
ContactID INT,
FirstName NVARCHAR(50),
LastName NVARCHAR(50)
)
INSERT #People (ContactID, FirstName, LastName)
EXEC dbo.GetPeopleByLastName #LastName = 'Alexander'

Get SQL Insert to work when PK is supplied or NOT

I have the following stored procedure:
ALTER Procedure dbo.APPL_ServerEnvironmentInsert
(
#ServerEnvironmentName varchar(50),
#ServerEnvironmentDescription varchar(1000),
#UserCreatedId uniqueidentifier,
#ServerEnvironmentId uniqueidentifier OUTPUT
)
WITH RECOMPILE
AS
-- Stores the ServerEnvironmentId.
DECLARE #APPL_ServerEnvironment TABLE (ServerEnvironmentId uniqueidentifier)
-- Insert the data into the table.
INSERT INTO APPL_ServerEnvironment WITH(TABLOCKX)
(
ServerEnvironmentName,
ServerEnvironmentDescription,
DateCreated,
UserCreatedId
)
OUTPUT Inserted.ServerEnvironmentId INTO #APPL_ServerEnvironment
VALUES
(
#ServerEnvironmentName,
#ServerEnvironmentDescription,
GETDATE(),
#UserCreatedId
)
-- If #ServerEnvironmentId was not supplied.
IF (#ServerEnvironmentId IS NULL)
BEGIN
-- Get the ServerEnvironmentId.
SELECT #ServerEnvironmentId = ServerEnvironmentId
FROM #APPL_ServerEnvironment
END
The ServerEnvironmentId column is a primary key with a default set on it, which is (newsequentialid()).
I need this stored procedure to work for 2 scenarios:
Value supplied for ServerEnvironmentId - WORKS.
Value not supplied for ServerEnvironmentId - DOES NOT WORK - CANNOT INSERT NULL VALUE. I thought by setting a default on this column this would be fine.
Someone please help to ammend this procedure so that it may work for both scenarios. Solution needs to have minimal changes as all sp's currently following this trend.
Default values are only applied on inserts if the column is not included in the INSERT list. I'd recommend the following not entirely trivial change (I've commented out the lines to be removed):
ALTER Procedure dbo.APPL_ServerEnvironmentInsert
(
#ServerEnvironmentName varchar(50),
#ServerEnvironmentDescription varchar(1000),
#UserCreatedId uniqueidentifier,
#ServerEnvironmentId uniqueidentifier OUTPUT
)
WITH RECOMPILE
AS
---- Stores the ServerEnvironmentId.
--DECLARE #APPL_ServerEnvironment TABLE (ServerEnvironmentId uniqueidentifier)
IF #ServerEnvironmentName is null
SET #ServerEnvironmentName = newid()
-- Insert the data into the table.
INSERT INTO APPL_ServerEnvironment WITH(TABLOCKX)
(
ServerEnvironmentName,
ServerEnvironmentDescription,
DateCreated,
UserCreatedId
)
--OUTPUT Inserted.ServerEnvironmentId INTO #APPL_ServerEnvironment
VALUES
(
#ServerEnvironmentName,
#ServerEnvironmentDescription,
GETDATE(),
#UserCreatedId
)
---- If #ServerEnvironmentId was not supplied.
--IF (#ServerEnvironmentId IS NULL)
--BEGIN
-- -- Get the ServerEnvironmentId.
-- SELECT #ServerEnvironmentId = ServerEnvironmentId
-- FROM #APPL_ServerEnvironment
--END
The default constraint will not be used by this procedure, but you can leave it in place if there are other places where rows may be added to the table.
(My first answer was long and so it this one, so I'm posting a second answer.)
I missed that you were using NewSequentialId. Again, if a column is specified within the insert statement, any DEFAULT values assigned to that column will not be used [unless you use the DEFAULT keyword in the INSERT statement, but that's still all or nothing--you can't say "if #Var is null then DEFAULT"]. I think you are stuck with simple branching and semi-redundant code, along the lines of:
ALTER Procedure dbo.APPL_ServerEnvironmentInsert
(
#ServerEnvironmentName varchar(50),
#ServerEnvironmentDescription varchar(1000),
#UserCreatedId uniqueidentifier,
#ServerEnvironmentId uniqueidentifier OUTPUT
)
WITH RECOMPILE
AS
-- Stores the ServerEnvironmentId.
DECLARE #APPL_ServerEnvironment TABLE (ServerEnvironmentId uniqueidentifier)
IF #ServerEnvironmentId is null
BEGIN
-- ServerEnvironmentId not provided by user, generate during the insert
INSERT INTO APPL_ServerEnvironment WITH(TABLOCKX)
(
ServerEnvironmentName,
ServerEnvironmentDescription,
DateCreated,
UserCreatedId
)
OUTPUT Inserted.ServerEnvironmentId INTO #APPL_ServerEnvironment
VALUES
(
#ServerEnvironmentName,
#ServerEnvironmentDescription,
GETDATE(),
#UserCreatedId
)
-- Get the new ServerEnvironmentId
SELECT #ServerEnvironmentId = ServerEnvironmentId
FROM #APPL_ServerEnvironment
END
ELSE
BEGIN
-- ServerEnvironmentId is provided by user
INSERT INTO APPL_ServerEnvironment WITH(TABLOCKX)
(
ServerEnvironmentName,
ServerEnvironmentDescription,
DateCreated,
UserCreatedId,
ServerEnvironmentId
)
OUTPUT Inserted.ServerEnvironmentId INTO #APPL_ServerEnvironment
VALUES
(
#ServerEnvironmentName,
#ServerEnvironmentDescription,
GETDATE(),
#UserCreatedId,
#ServerEnvironmentId
)
END
(Why lock the entire table during the insert?)
Help to Simplify SQL Insert which uses NEWSEQUNETIALID() column default