Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SP_EXECUTESQL and Output Parameter

I would like get the ID from the query, but I am getting a NULL, where is my mistake?

DECLARE @TblZimz    NVARCHAR(256)
DECLARE @IdModul    INTEGER
DECLARE @Id         INTEGER

SET @TblZimz        = '_ZIMZ000001'
SET @IdModul        = 1
--SET @Id               = -1

EXECUTE [InsertZimz] @TblZimz, @IdModul, @Id OUTPUT




ALTER PROCEDURE [InsertZimz]
@TblZimz    NVARCHAR(256)
, @IdModul  NVARCHAR(256)
, @Id       INTEGER OUTPUT

            DECLARE @SqlQuery NVARCHAR(MAX)
        SET @SqlQuery = 'SELECT TOP (1) ([ID]) FROM ' + @TblZimz + ' WHERE [ModulId] = ' + @IdModul

        EXEC SP_EXECUTESQL @SqlQuery, N'@Id INTEGER OUTPUT', @Id OUTPUT

why the @Id Paramter is alwasy null? I cant see my mistake?

like image 585
MeerArtefakt Avatar asked Dec 15 '14 14:12

MeerArtefakt


2 Answers

First, select the desired id in an output variable using @Id = ([ID]) then assign this @Id OUTPUT value in the @Id variable using @Id = @Id OUTPUT. Also, you should pass data in where clause using a variable to avoid sql injection problem like [ModulId] = @IdModul (i.e. you should not concatenate it like [ModulId] = ' + @IdModul). try this :

DECLARE @SqlQuery NVARCHAR(MAX)

SET @SqlQuery = 'SELECT TOP (1) @Id = ([ID]) FROM '
                + @TblZimz + ' WHERE [ModulId] = @IdModul'

EXEC SP_EXECUTESQL
  @SqlQuery,
  N'@Id INT OUTPUT, @IdModul INT',
  @IdModul = @IdModul,
  @Id = @Id OUTPUT 

Check details of SP_EXECUTESQL here

like image 60
Deep Avatar answered Oct 15 '22 17:10

Deep


Like Deepak's answer, but easier:

EXEC SP_EXECUTESQL @SqlQuery,
N'@Id INT OUTPUT, @IdModul INT',
@IdModul OUTPUT, @Id

like image 35
Eric Draven Avatar answered Oct 15 '22 17:10

Eric Draven