eekinci
eekinci

Reputation: 839

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?

Upvotes: 15

Views: 37673

Answers (3)

bwperrin
bwperrin

Reputation: 692

Here's an example of returning a dynamically defined proc's return value (rather than dataset results):

CREATE PROC p AS return 3
GO
DECLARE @proc varchar(30) = 'p', @retval int
DECLARE @qry nvarchar(max) = 'EXEC @i = ' + @proc --plus params as needed
EXEC sp_executesql @qry, N'@i INT OUTPUT', @retval OUTPUT
select @retval      --returns 3

(Use case: for a full "data run," I cursor through a list of procs to execute, each of which returns a row count for logging purposes. Chased my tail a good while before cracking this.)

Upvotes: 2

Eric Draven
Eric Draven

Reputation: 255

Like Deepak's answer, but easier:

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

Upvotes: 2

Deep
Deep

Reputation: 3202

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

Upvotes: 29

Related Questions