0

I have a situation where I may need to pass a variable that could possibly hold a NULL value to a function, but through sp_executesql, so I will need to convert it to string value via string concatenation.

For Example:

declare @var1 varchar(10) = 'value'
declare @var2 varchar(10) = null
declare @sql nvarchar(2000)
.
.
set @sql = '
  select dbo.fn_Scalar(''' + @var1 + ''', ''' + @var2 + ''' )
'

Function Definition:

Create Function [dbo].[fn_fn_Scalar] 
(
    @var1 varchar(10) ,
    @var2 varchar(10) = null
) RETURNS float
AS BEGIN
  Declare @ret float

  Select @ret = sum(value)
  from Table
  where Field1 = @var1
    and Field2 like isnull(@var2, '%')

  return @ret
END

What would be the best approach to allow for fn_Scalar to be called via Dynamic and Static SQL statements and still allow for the second parameter to either be set to a value, NULL, or default.

1 Answer 1

2

You can pass parameters to sp_executesql function like so:

declare @var1 varchar(10) = 'value'
declare @var2 varchar(10) = null
Set @ParamDefinition = '@var1 varchar(10), @var2 varchar(10)'

Execute sp_Executesql 'select dbo.fn_Scalar(@var1,@var2)', @ParamDefinition, @var1, @var2
Sign up to request clarification or add additional context in comments.

3 Comments

Good, forgot about running a parameterized query like that. Off-topic Side note: Will executing this style of SQL help mitigate Injections?
It helps prevent SQL Injections, as long as it's used properly.
as with most tools, misuse is very dangerous.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.