Purpose
The purpose of this page is to show an example of getting the current PK value of the last inserted row of data which, in some cases, can eliminate the need for a Select clause.
CREATE TABLE #tmpWork (
rowID INT PRIMARY KEY IDENTITY(1, 1)
,guidNum UNIQUEIDENTIFIER NULL
,guidName VARCHAR(150) NULL
);
DECLARE @PKValue INT = 0;
DECLARE @RetrieveCount = 0;
SET NOCOUNT ON;
-- Add Rows
INSERT INTO #tmpWork (guidName) VALUES ('Sample Name 1'); -- insert this to set PK 1 for row 1 with a row count of 1.
INSERT INTO #tmpWork (guidName) VALUES ('Sample Name 2'); -- insert this to show the PK greater than 1 with a row count of 1.
-- Get row count after last row inserted; as 2 separate INSERT statements were performed, this will actually be 1.
-- If you want to get a row count of 2, the INSERT statement must contain both. In that case, use this INSERT statement instead:
-- INSERT INTO #tmpWork (guidName) VALUES ('Sample Name 1'), ('Sample Name 2');
SET @RetrieveCount = @@ROWCOUNT;
-- Get the PK of the last row inserted (2)
SET @PKValue = SCOPE_IDENTITY();
SELECT * FROM #tmpWork;
SELECT @PKValue AS 'PK', @RetrieveCount AS 'Row Count';
-- Cleanup
IF OBJECT_ID('tempdb...#tmpWork') IS NOT NULL
BEGIN
DROP TABLE #tmpWork;
END