views:

180

answers:

2

How can I alter Update Stored Procedure so if developer want to set only Size then he/she does not requireed to pass TimeStamp. Moreover, then what will be execute code for this procedure?

Scenario:

Update TimeStamp = getdate() field whose SizeID = 1 AND Size =Large

Note: This field Parameters and condition parameters must be dynamic and optionals like in where TimeStamp can also be supplied.

Update Stored Procedure:

ALTER PROCEDURE [dbo].[SP_Sizes_Update]

@SizeID    int,
@Size    varchar(50),
@TimeStamp    datetime

AS

Update Sizes

Set
    Size = @Size,
    TimeStamp = @TimeStamp
Where

SizeID = @SizeID
+3  A: 

Just set the parameter to a default value, like this:

ALTER PROCEDURE [dbo].[SP_Sizes_Update]
  @SizeID    int,
  @Size    varchar(50),
  @TimeStamp    datetime = null
AS
  Update Sizes
  Set
   Size = @Size,
   TimeStamp = @TimeStamp
  Where
   SizeID = @SizeID

however, if you want the default value to be a result of a function call, you could use some special value that will be replaced by the function hole, like this:

ALTER PROCEDURE [dbo].[SP_Sizes_Update]
  @SizeID    int,
  @Size    varchar(50),
  @TimeStamp    datetime = null
AS
  if @TimeStamp is null
   set @TimeStamp = getdate()

   Update Sizes
   Set
     Size = @Size,
     TimeStamp = @TimeStamp
   Where SizeID = @SizeID
SWeko
+1, although for something named @TimeStamp, I'd probably set the default value to getdate().
SirDemon
@SirDemon - you can't use GETDATE() as a default parameter value, has to be a constant
AdaTheDev
@Ada - I think SirDemon was talking about setting the default value of the column in the table as Getdate(), however, that won't work with update calls.
SWeko
@SWeko, I pretty much meant what you've already added to your answer. I simply wouldn't have left a @timestamp to be null.
SirDemon
+3  A: 

one way

ALTER PROCEDURE [dbo].[SP_Sizes_Update]
  @SizeID    int,
  @Size    varchar(50) = 'Large',
  @TimeStamp    datetime = null
AS
  Update Sizes
  Set
   Size = @Size,
   TimeStamp = coalesce(@TimeStamp,getdate())
  Where
   SizeID = @SizeID
SQLMenace
+1 for more concise
AdaTheDev