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?
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 Deepak's answer, but easier:
EXEC SP_EXECUTESQL @SqlQuery,
N'@Id INT OUTPUT, @IdModul INT',
@IdModul OUTPUT, @Id
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With