Hi everybody. I noticed a strange behaviour using a 'select into' statement with an identity column in source table.Usually I put the identity field in a cast statement in order to avoid its propagation in destination table, as follow:[b]SELECT MyIdentity = convert(int, b.MyIdentity) INTO #t FROM [i]MyTable1 [/i]aLEFT JOIN MyView2 b ON a.MyId = b.ExternalId[/b]Statement returns a one col / one row result set with a null value.In sample MyTable1 is a physical table and MyView2 is a view (a simple 'select * from MyTable2'). Everything works fine.I need to replace MyTable1 with a view with fixed values that returns the same result set (for performance purpose), and change my statement as follow[b]SELECT MyIdentity = convert(int, b.MyIdentity) INTO #t FROM [i]MyView1 [/i]aLEFT JOIN MyView2 b ON a.MyId = b.ExternalId[/b]When I execute this statement an error is raised: "[b]Attempting to set a non-NULL-able column's value to NULL.[/b]"It seems that the convert function does not work anymore by view usage. I noticed that qep are different for the two statements: by using the view I have a [i]Compute Scalar operator ([Expr1007] = Scalar Operator(setidentity([test].[dbo].[MyTable2].[MyIdentity],(-7),(0),N'#t')))[/i] that is missing by using the table, and this operator is the cause of my error.QEP using table:[img]https://social.msdn.microsoft.com/Forums/getfile/862617[/img]QEP using view:[img]https://social.msdn.microsoft.com/Forums/getfile/862615[/img]Briefly, by second statement 'Select * into' creates a table that inherit identity column, regardless to 'convert' operation. So the insert phase fails, because the join returns a null value. By the first statement no 'Scalar Operator(setidentity...' is used in qep and everything is ok.It seems a strange behaviour, very annoying if you need to build all your Tsql dinamically. Have you some explanation about?Here there's the code to reproduce the issue:[quote]CREATE TABLE [dbo].[MyTable1]([MyId] [int] NULL)INSERT INTO [dbo].[MyTable1] VALUES (1)GOCREATE TABLE [dbo].[MyTable2]([MyIdentity] [int] IDENTITY(1,1) NOT NULL, [ExternalId] [int] NOT NULL)INSERT INTO [dbo].[MyTable1] VALUES (2)INSERT INTO [dbo].[MyTable1] VALUES (3)GOCREATE VIEW [dbo].[MyView1] as SELECT MyId = 1GOCREATE VIEW [dbo].[MyView2] as SELECT * FROM MyTable2GO-- OKSELECT MyIdentity = convert(int, b.MyIdentity) INTO #t FROM MyTable1 aLEFT JOIN MyView2 b ON a.MyId = b.ExternalIddrop table #t-- KOSELECT MyIdentity = convert(int, b.MyIdentity) INTO #t FROM MyView1 aLEFT JOIN MyView2 b ON a.MyId = b.ExternalId[/quote]Thanks!
↧