Stored Procedures - Do you keep your Stored Procedures simple?
Loading last updated info...
If you are using the .NET Framework, put validation and defaults in the middle tier. The backend should have the required fields (Allow Nulls = False), but no complicated constraints. The following are examples that work with the Products table (with an added timestamp field called Concurrency) from Northwind.
1. Code: Select Procedure
ALTER PROCEDURE dbo.ProductSelect@ProductID intASSELECT ProductName, SupplierID, CategoryID, QuantityPerUnit, UnitPrice, UnitsInStock,UnitsOnOrder, ReorderLevel, Discontinued, ConcurrencyFROM ProductsWHERE (ProductID= @ProductID)
2. Code: Insert Procedure
ALTER PROCEDURE dbo.ProductInsert@ProductName nvarchar(40),@SupplierID int,@CategoryID int,@QuantityPerUnit nvarchar(20),@UnitPrice money,@UnitsInStock smallint,@UnitsOnOrder smallint,@ReorderLevel smallint,@Discontinued bitASINSERT INTO Products (ProductName, SupplierID, CategoryID, QuantityPerUnit, UnitPrice,UnitsInStock, UnitsOnOrder, ReorderLevel, Discontinued)VALUES (@ProductName, @SupplierID, @CategoryID, @QuantityPerUnit, @UnitPrice, @UnitsInStock,@UnitsOnOrder, @ReorderLevel, @Discontinued, 1)SELECT Scope_Identity() AS [SCOPE_IDENTITY] --If table has identity column--SELECT @@ROWCOUNT --If table doesn't have identity column-- Note: The middle tier must check the ROWCOUNT = 1
3.Code: Update Procedure
ALTER PROCEDURE dbo.ProductUpdate@ProductID int,@ProductName nvarchar(40),@SupplierID int,@CategoryID int,@QuantityPerUnit nvarchar(20),@UnitPrice money,@UnitsInStock smallint,@UnitsOnOrder smallint,@ReorderLevel smallint,@Discontinued bit,@Concurrency timestampUPDATE ProductsSET ProductName = @ProductName,SupplierID = @SupplierID,CategoryID = @CategoryID,QuantityPerUnit = @QuantityPerUnit,UnitPrice = @UnitPrice,UnitsInStock = @UnitsInStock,UnitsOnOrder = @UnitsOnOrder,ReorderLevel = @ReorderLevel,Discontinued = @DiscontinuedWHERE (Concurrency = @Concurrency) AND (ProductID= @ProductID) --Note the double criteria to ensure concurrencySELECT @@ROWCOUNT-- Note: The middle tier must check the ROWCOUNT = 1
4.Code: Delete Procedure
ALTER PROCEDURE dbo.ProductDelete@ProductID int,@Concurrency timestampASDELETE FROM ProductsWHERE (ProductID= @ProductID) AND (Concurrency = @Concurrency)--Note the double criteria to ensure concurrencySELECT @@ROWCOUNT--Note: The middle tier must check the ROWCOUNT = 1