问题描述
我想从查询中获取 ID,但我得到的是 NULL,我的错误在哪里?
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
为什么@Id 参数总是为空?我看不到我的错误?
why the @Id Paramter is alwasy null? I cant see my mistake?
推荐答案
首先,使用 @Id = ([ID])
在输出变量中选择所需的 id
然后使用 @Id = @Id OUTPUT
在 @Id
变量中分配这个 @Id OUTPUT
值.此外,您应该使用变量在 where 子句中传递数据以避免像 [ModulId] = @IdModul
这样的 sql 注入问题(即您不应该像 [ModulId] = ' + @IdModul 那样连接它
).试试这个:
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
查看 SP_EXECUTESQL
的详细信息此处
这篇关于SP_EXECUTESQL 和输出参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!