Stored Procedures - Do you avoid using SELECT * when inserting data?
Updated by Brook Jeynes [SSW] 1 year ago. See history
Using a statement like "INSERT tableName SELECT * FROM otherTable", makes your stored procedures vulnerable to failure. Once either of the two tables change, your stored procedure won't work. Not only that, when the inserting table has an identity column, such a statement will cause an error - "An explicit value for the identity column in table ParaRight can only be specified when a column list is used and IDENTITY_INSERT is ON."
USE [ParaGreg]GO/****** Object: StoredProcedure [dbo].[procMove] Script Date: 08/08/2008 12:18:33 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOALTER PROCEDURE [dbo].[procMove]@id AS Char,@direction AS INTASIF @direction = 0BEGININSERT INTO ParaRightSELECT * FROM ParaLeftWHERE ParaID = @idDELETE FROM ParaLeftWHERE ParaID = @idENDELSE IF @direction = 1BEGININSERT INTO ParaLeftSELECT * FROM ParaRightWHERE ParaID = @idDELETE FROM ParaRightWHERE ParaID = @idEND
❌ Figure: Figure: Bad Example - Using SELECT * when inserting data. Besides, this stored procedure should have an Else section to raise error when no condition is satisfied
USE [ParaGreg]GO/****** Object: StoredProcedure [dbo].[procMove] Script Date: 08/08/2008 12:18:33 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOALTER PROCEDURE [dbo].[procMove]@id AS Char,@direction AS INTASIF @direction = 0BEGININSERT INTO ParaRightSELECT Col1,Col2 FROM ParaLeftWHERE ParaID = @idDELETE FROM ParaLeftWHERE ParaID = @idENDELSE IF @direction = 1BEGININSERT INTO ParaLeftSELECT * FROM ParaRightWHERE ParaID = @idDELETE FROM ParaRightWHERE ParaID = @idENDELSE BEGIN PRINT "Please use a correct direction"END
✅ Figure: Figure: Good Example - Using concrete columns instead of * and provide an Else section to raise errors