0

How to use numeric variable in sql statement inside procedure?
This is my try:

create procedure ##sp_check (

    @tolerance numeric
)

AS

Declare @SQL nvarchar(max)
SET @SQL = '
SELECT
    *
FROM
    a
WHERE
    value > @tolerance
'
    exec sp_executesql @SQL

go

exec ##sp_check 1

and the ERROR: Must declare the scalar variable "@tolerance".
I think this is because the variable is invisible between ' and ' so I can do it by declaring @tolerance as varchar and in sql statement converting it into numeric but its a bit confusing...

3 Answers 3

1

You have to explicitly pass the variable into the sp_executesql (it runs in a different scope that doesn't have access to variables declared in the calling scope).

SET @SQL = 'SELECT * FROM a WHERE value > @t'
exec sp_executesql @SQL, N'@t numeric', @t=@tolerance
Sign up to request clarification or add additional context in comments.

5 Comments

what this N means?
oh I guess the N before ' ' says that in brankets is numeric value not character
N means NVARCHAR since sp_executesql wants nvarchar parameters
and how modify this when I wanna inject 2 variables or more?
oh, it goes like this, then: exec sp_executesql @SQL, N'@var1 decimal(10,2), @var2 decimal(10,2)', @var1= @var1, @var2= @var2
1

I wonder why you're using Dynamic SQL here.. try this:

create procedure ##sp_check (

    @tolerance numeric
)

AS

SELECT * FROM a WHERE value > @tolerance

go

exec ##sp_check 1

Comments

0

You can't reference a variable declared outside of a dynamic statement inside it. Thus, the correct syntax would be:

CREATE PROC ##sp_check (@tolerance numeric)
AS

    DECLARE @SQL nvarchar(max)
    SET @SQL = N'SELECT *' + NCHAR(10) +
               N'FROM a' + NCHAR(10) +
               N'WHERE value > @dtolerance;';
    PRINT @SQL;
    EXEC sp_executesql @SQL, N'@dtolerance numeric',@dtolerance = @tolerance;

go

exec ##sp_check 1;

I suggest, however, you declare your scale and precision on your numeric, it's very bad practice to not do so.

Comments

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.