HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Update column based on input variable in stored procedure

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
storedupdatecolumnprocedureinputbasedvariable

Problem

The purpose of the below code is to update a column based on the name of the field name sent from the .NET code. This allows one piece of code to handle multiple rows when a user is only adding/updating one at a time.

I have been using Stored Procedures for a while but normally just Add/Update but not using variable field names. All tips appreciated.

USE DB
GO
/****** Object:  StoredProcedure [dbo].[spActionUpdateOldestDate]    Script Date: 04/02/2014 14:24:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spUpdateViaFieldName] 

-- spActionUpdateOldestDate '1234','date','field'
-- Add the parameters for the stored procedure here
@AlphaNumbericalRef nvarchar(50)            
,@vValue nvarchar(MAX) 
 ,@vFieldName varchar(MAX)

AS
BEGIN

-- add selection for courseID etc.. here
Execute ('UPDATE [TblActionsOldest] SET ' + @vFieldName + ' = ''' + @vValue + ''' WHERE RefID = ''' + @AlphaNumbericalRef+ '''')

END

Solution

I think your stored procedure looks great!

The only line that had me scratching my head is this one:

Execute ('UPDATE [TblActionsOldest] SET ' + @vFieldName + ' = ''' + @vValue + ''' WHERE RefID = ''' + @AlphaNumbericalRef+ '''')


I'm guessing those apostrophes are escape characters for asp.net but if that's not the case I would discard them.
Nice work!

Code Snippets

Execute ('UPDATE [TblActionsOldest] SET ' + @vFieldName + ' = ''' + @vValue + ''' WHERE RefID = ''' + @AlphaNumbericalRef+ '''')

Context

StackExchange Code Review Q#46060, answer score: 3

Revisions (0)

No revisions yet.