Share auto-increment value from SQL stored procedure - sql

I have a stored procedure that inserts data on a table with an auto-increment id (name of 'requestid'). As I insert data into it using the procedure, I want to take the value of the auto-increment field and use it on another query to the same stored procedure. How do I do that? Thank you in advance for your time.
CREATE PROCEDURE [dbo].[sp_Create_new_request]
#employeeid INT ,
#requestdate DATETIME ,
#deliverdate DATETIME ,
#totalcost MONEY
AS
BEGIN
INSERT INTO dbo.Requests
(
EmployeeID ,
RequestDate ,
DeliverDate ,
TotalCost
)
VALUES
(
#employeeid ,
#requestdate ,
#deliverdate ,
#totalcost
)
END

Try
CREATE PROCEDURE [dbo].[sp_Create_new_request]
#employeeid INT ,
#requestdate DATETIME ,
#deliverdate DATETIME ,
#totalcost MONEY,
requestid INT = NULL OUT
AS
BEGIN
INSERT INTO dbo.Requests
(
EmployeeID ,
RequestDate ,
DeliverDate ,
TotalCost
)
VALUES
(
#employeeid ,
#requestdate ,
#deliverdate ,
#totalcost
)
SET #requestid = SCOPE_IDENTITY();
END

You should not use auto increment instead use sequence to increment and then you can reuse that value anywhere.

You can use also :
IDENT_CURRENT ('dbo.Requests')
Information about IDENT_CURRENT
http://technet.microsoft.com/en-us/library/ms175098.aspx

Related

Removing a column name from a stored procedure

I created a stored procedure for insert query and run the code. Successfully it executed. Now I want to remove one column from from that SP. How to do it?
CREATE PROCEDURE dbo.NewTerms_Insert
#ListID nvarchar(50) ,
#TimeCreated datetime ,
#TimeModified datetime ,
AS
BEGIN
SET NOCOUNT ON
INSERT INTO dbo.NewTerms
(
ListID ,
TimeCreated ,
TimeModified ,
)
VALUES
(
#ListID ,
#TimeCreated ,
#TimeModified ,
)
END
GO
I want to remove ListID from this Stored Procedure named dbo.NewTerms_Insert. How to do it?
Just ALTER the procedure with removing that column.
ALTERPROCEDURE dbo.NewTerms_Insert
#TimeCreated datetime ,
#TimeModified datetime ,
AS
BEGIN
SET NOCOUNT ON
INSERT INTO dbo.NewTerms
(
TimeCreated ,
TimeModified ,
)
VALUES
(
#TimeCreated ,
#TimeModified ,
)
END
GO
Remove the column and alter the procedure:
ALTER PROCEDURE dbo.NewTerms_Insert
#TimeCreated datetime ,
#TimeModified datetime
AS
BEGIN
SET NOCOUNT ON
INSERT INTO dbo.NewTerms
(
TimeCreated ,
TimeModified
)
VALUES
(
#TimeCreated ,
#TimeModified
)
END
GO
Simply modify the procedure as you want (changing its interface and/or its body).
Before executing that script, run the following in order to make sure the previous version is removed:
IF OBJECT_ID('dbo.NewTerms_Insert', 'P') IS NOT NULL
DROP PROCEDURE dbo.NewTerms_Insert;
GO
Personally, I find it good practise to insert that fragment at the beginning of each script that creates/modifies a procedure or whatever.
Alter procedure and remove list column from insert statement and from value
Alter PROCEDURE dbo.NewTerms_Insert
(
#ListID nvarchar(50) ,
#TimeCreated datetime ,
#TimeModified datetime
)
AS
BEGIN
SET NOCOUNT ON
INSERT INTO dbo.NewTerms
(
TimeCreated ,TimeModified
)
VALUES
(
#TimeCreated ,
#TimeModified
)
END
GO

SQL IDENTITIY Column not starting with 1

I have a temp table in SQL 2014. In this table variable I have an identity column declared.
DECLARE #TempTable TABLE
(
ID int IDENTITY(1,1) PRIMARY KEY
, IncidentResolvedOn date
, IncidentCreatedOn date
, IncidentClosedOn date
, TaskAssigned date
, TaskCompleted date
, TaskID float
, IncidentTeamID int
, TotalDaysOutstanding int
, TierInfo varchar(15)
, Task_NoTask varchar(15)
, Tier_2_Days_Outstanding int
, Tier_1_Days_Outstanding int
, DaysToResolve int
, BadDays int
, StartDate date
, EndDate date
)
When I run the rest of the query the ID column sometimes doesn't start with 1, instead it starts with some random number. The code below is what I use to insert into this table variable.
INSERT INTO #TempTable(IncidentResolvedOn, IncidentCreatedOn, IncidentClosedOn,TaskAssigned, TaskCompleted, TaskID, IncidentTeamID )
SELECT [Incident Resolved On]
, [Incident Created On]
, [Incident Closed On]
, [Task Assigned On]
, [Task Completed On]
, [Task ID]
, IncidentTeamID
FROM HEATData
This happens in both a table variable and temp table. I've never seen this happen before. Usually when I use the IDENTITY(1,1) phrase it always starts with 1 no matter how many times I create that table. Any suggestions out there?
I imagine your connection is staying open and thus, your identity isn't resetting for your local variable. Here's an example.
DECLARE #TempTable TABLE
(
ID int IDENTITY(1,1) PRIMARY KEY,
ID2 int)
insert into #TempTable
values
(1),(2)
select * from #TempTable
delete from #TempTable
insert into #TempTable
values
(1),(2)
select * from #TempTable
Now, if you'd wrap this in it's own batch using GO you could see this wouldn't happen. In fact, you have to re-declare your table variable.
DECLARE #TempTable TABLE
(
ID int IDENTITY(1,1) PRIMARY KEY,
ID2 int)
insert into #TempTable
values
(1),(2)
select * from #TempTable
go
DECLARE #TempTable TABLE
(
ID int IDENTITY(1,1) PRIMARY KEY,
ID2 int)
insert into #TempTable
values
(1),(2)
select * from #TempTable
This would be the same for a #TempTable as well if you didn't explicitly drop the #TempTable or the connection remained open. Of course, for actual tables the increment will continue similarly to the first examaple.

How to pass constant value in stored procedure

I have the following statement inside a stored procedure:
INSERT INTO #tblThreatenedSpeciesSubzone
(ThreatenedSpeciesZoneID,
ManagementZoneID,
VegetationZoneID)
SELECT *
FROM OPENXML (#hDoc, '/NewDataSet/tblThreatenedSpeciesSubzone', 2)
WITH (ThreatenedSpeciesZoneID INT,
ManagementZoneID INT,
VegetationZoneID INT) XMLDATA
WHERE VegetationZoneID = #VegetationZoneIDInXML
Sometime "managementZone id" becomes null, I want to replace if it is null then I want pass the constant value "0". Is there a way to do ?
Not sure about "passing a constant value", but you can always set a default:
CREATE PROCEDURE Sales.uspGetSalesYTD
#SalesPerson nvarchar(50) = 'Andersson' -- default value
AS
So:
#ManagementZoneID INT = 0
You could use a coalesce in the select statement
INSERT INTO #tblThreatenedSpeciesSubzone
( ThreatenedSpeciesZoneID ,
ManagementZoneID ,
VegetationZoneID
)
SELECT
ThreatenedSpeciesZoneID ,
COALESCE(ManagementZoneID,0) ,
VegetationZoneID
FROM OPENXML (#hDoc, '/NewDataSet/tblThreatenedSpeciesSubzone', 2)
WITH ( ThreatenedSpeciesZoneID INT ,
ManagementZoneID INT ,
VegetationZoneID INT ) XMLDATA
WHERE VegetationZoneID = #VegetationZoneIDInXML

Trouble with OUTPUT statement. Incorrect Syntax

I am trying to update a data set based on one conditional and then retrieving all the updated rows. VS keeps telling me there is an incorrect syntax error near my OUTPUT clause but I do not see anything wrong. I am just trying to figure out how to use "OUTPUT" so this may be a very stupid mistake I am making but failing to see.
What is wrong (syntactically) with this OUTPUT clause?
CREATE PROCEDURE [dbo].[GetInitialSessionNotifications]
#CurrentSessionId bigint
AS
DECLARE #tempTable table(
id bigint NOT NULL,
[Type] nvarchar,
DocumentCommentID bigint,
AnnouncmentID int,
EventID int,
MeetingID int,
[Read] bit,
RecieverId int,
AnnouncmentCommentId bigint,
EventCommentId bigint,
MeetingCommentId bigint,
DateAndTime DateTime);
UPDATE Notifications SET SessionId = #CurrentSessionId
WHERE SessionId != #CurrentSessionId
OUTPUT INSERTED.id,
INSERTED.[Type],
INSERTED.DocumentCommentID,
INSERTED.AnnouncmentID,
INSERTED.EventID,
INSERTED.MeetingID,
INSERTED.[Read],
INSERTED.RecieverId,
INSERTED.AnnouncmentCommentId,
INSERTED.EventCommentId,
INSERTED.MeetingCommentId,
INSERTED.DateAndTime
INTO #tempTable;
SELECT id, [Type], DocumentCommentId, AnnouncmentID, EventID, MeetingID,
[Read], RecieverId, AnnouncmentCommentId, EventCommentId, MeetingCommentId, DateAndTime
FROM #tempTable;
RETURN 0
Try this one -
CREATE PROCEDURE [dbo].[GetInitialSessionNotifications]
#CurrentSessionId BIGINT
AS BEGIN
DECLARE #tempTable TABLE
(
id BIGINT NOT NULL ,
[Type] NVARCHAR ,
DocumentCommentID BIGINT ,
AnnouncmentID INT ,
EventID INT ,
MeetingID INT ,
[Read] BIT ,
RecieverId INT ,
AnnouncmentCommentId BIGINT ,
EventCommentId BIGINT ,
MeetingCommentId BIGINT ,
DateAndTime DATETIME
)
UPDATE Notifications
SET SessionId = #CurrentSessionId
OUTPUT
INSERTED.id ,
INSERTED.[Type] ,
INSERTED.DocumentCommentID ,
INSERTED.AnnouncmentID ,
INSERTED.EventID ,
INSERTED.MeetingID ,
INSERTED.[Read] ,
INSERTED.RecieverId ,
INSERTED.AnnouncmentCommentId ,
INSERTED.EventCommentId ,
INSERTED.MeetingCommentId ,
INSERTED.DateAndTime
INTO #tempTable
WHERE SessionId != #CurrentSessionId
SELECT id ,
[Type] ,
DocumentCommentId ,
AnnouncmentID ,
EventID ,
MeetingID ,
[Read] ,
RecieverId ,
AnnouncmentCommentId ,
EventCommentId ,
MeetingCommentId ,
DateAndTime
FROM #tempTable;
END

Insert into temp table from stored procedure generating distributed transaction error in SQL 2000

Similar to Insert into a temp table from a stored procedure on Sql Server 2000 from last year, but now with a strange error.
I'm using Microsoft SQL Server 2000 to dump results from one stored procedure into the temp table of another procedure. Both procedures are on the same physical server, yet I'm getting an error message as if the second procedure was on a different server.
The operation could not be performed
because the OLE DB provider 'SQLOLEDB'
was unable to begin a distributed
transaction.
The code:
CREATE TABLE
#subjects (
subject_id INT NULL
, subject_name NVARCHAR(500) NULL
, crm_company_id INT NULL
, customer_no NVARCHAR(10) NULL
, order_no NVARCHAR(10) NULL
, order_date DATETIME NULL
, state_code NVARCHAR(2) NULL
, filing_office NVARCHAR(35) NULL
, jurisdiction NVARCHAR(200) NULL
, invoice_no NVARCHAR(10) NULL
, invoice_date DATETIME NULL
, invoice_status NVARCHAR(10) NULL
)
INSERT INTO #subjects (subject_id,subject_name,crm_company_id,customer_no,order_no,order_date,state_code,filing_office,jurisdiction,invoice_no,invoice_date,invoice_status)
EXECUTE webapp.dbo.subject_search
#SubjectName = #SubjectName
, #StartDate = #StartDate
, #EndDate = #EndDate
, #CRMCompanyID = #CRMCompanyID
, #RoleName = #RoleName
can you post the code of the subject_search procedure, are there any linked servers involved, are there also any distributed transaction inside the code?