Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

MS SQL Server 2014: Error inserting into Temp table with index and identity field

$
0
0

Dear colleagues,

The code below works perfectly fine on MS SQL Server 2008 R2 and MS SQL Server 2012, but gives an error every second time the proc is executed on MS SQL Server 2014. If I do not define any index on the temp table, the problem disappears. Defining the index after the insert, does not help. Does anybody have any suggestions on how to solve this? In my real life proc, I need the index for performance reasons. Should this be reported as a bug in MS SQL Server 2014?

Thanks.

SET NOCOUNT ON
GO
IF EXISTS (SELECT 1 FROM sys.procedures WHERE name = 'usp_Test') DROP PROC dbo.usp_Test;
GO
CREATE PROC dbo.usp_Test AS
BEGIN
   SET NOCOUNT ON

   CREATE TABLE #Source(ID integer NOT NULL);
   INSERT INTO #Source VALUES (1), (2), (3);
   CREATE TABLE #Dest (ID integer IDENTITY(1,1) NOT NULL);
   CREATE INDEX #IDX_Dest ON #Dest (ID);

   PRINT 'Check if the insert might cause an identity crisis';
   SELECT 'Source' AS SourceTable, * FROM #Source;
   SELECT 'Destination' AS DestTable, * FROM #Dest;

   SET IDENTITY_INSERT #Dest ON;
   PRINT 'Do the insert';
   INSERT INTO #Dest (ID) SELECT ID FROM #Source;
   PRINT 'Insert ready';
   SET IDENTITY_INSERT #Dest OFF;
   SELECT * FROM #Dest;

   DROP TABLE #Source;
   DROP TABLE #Dest;
END;
GO

PRINT 'First execution of the proc, everything OK';
EXEC dbo.usp_Test;
PRINT '';
PRINT 'Second execution of the proc, the insert fails.';
PRINT 'Removing the index #IDX_Dest causes the error to disappear.';
EXEC dbo.usp_Test;
GO

DROP PROC dbo.usp_Test;
GO


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>