Parameter - Best Practices

For each data type fo a Database profile there is a good practice how to use the parameter in SQL:

Character

See also Null and/or empty Strings

declare @userID  as varchar(50)     = ? -- Parameter 1
if( len(@userID  ) =0 ) set @userID  =null
if( @userID is null) RAISERROR( 'UserId must not be (null)!', 17, 0 );

Numbers and Bits (boolean)

Use the implicit conversion when possible. However, consider values can be null, when the platform sent an empry string.

declare @isActive bit = cast( ? as bit) -- exception if ? is not "castable"

declare @function as int = ?
if( @function is null) RAISERROR( 'No function specified!', 17, 0 );

Explicit conversion

declare @expectedTotalString as varchar(20) = ?

declare @expectedTotal as decimal(10,2) = TRY_CONVERT(decimal(10,2), @expectedTotalString)
if @expectedTotal IS NULL
    RAISERROR( N'ExpectedTotal is not a number', 17, 0)
if @expectedTotal <= 0
    RAISERROR( N'Invalid ExpectedTotal %s ', 17, 0, @expectedTotalString )

More

Last updated