【问题标题】:sp_executesql Cross Server Insert return Scope_Identity()sp_executesql 跨服务器插入返回 Scope_Identity()
【发布时间】:2017-03-28 19:40:21
【问题描述】:

我已经找到了我的问题的答案,他们都说下面的语法应该有效。它对我不起作用。我的输出变量始终为NULL,因此我们将不胜感激。

DECLARE @SqlCommand NVARCHAR(1000),
              @ParamDefinition nvarchar(500),
              @Id INT

SET @SqlCommand = N'INSERT INTO [server].db.dbo.table(Title) VALUES(''Insert Into table From othertable Test'')  SELECT @Id = SCOPE_IDENTITY()'
SET @ParamDefinition = N'@Id integer OUTPUT'

EXECUTE sp_executesql @SqlCommand, @ParamDefinition, @Id OUTPUT

Select @Id

我的Select @Id 每次都返回NULL,但是该行被插入到表中。

我在 Stack Overflow 上发现了四五个结果,表明我的代码应该可以工作并且应该返回 ID。但事实并非如此。

我正在使用第三方服务器,是否有可能引发我没有看到的错误。

感谢您的帮助。

注意:下面的语句返回 Scope_Identity() 的值。问题是我不知道如何在变量中捕获该值。

EXEC [Server].[db].[dbo].sp_executesql N'
     INSERT INTO [server].db.dbo.table(Title) VALUES(''Test Title Insert'')
     SELECT SCOPE_IDENTITY()'

我尝试了下面的语法,但没有成功

DECLARE @Id INT

EXEC @Id = [Server].[db].[dbo].sp_executesql N'
     INSERT INTO [server].db.dbo.table(Title) VALUES(''Test Title Insert'')
     SELECT SCOPE_IDENTITY()'

选择@Id - @Id 始终为 NULL。

【问题讨论】:

    标签: scope identity sp-executesql


    【解决方案1】:

    您在第一个 sn-p 中的参数定义应该使用int 而不是integer

    此外,您可以尝试使用this question 中解释的 OUTPUT 关键字。

    【讨论】:

    • 我把参数定义改成int,变量还是返回NULL。
    • @Alwelder 尝试在链接问题中使用 OUTPUT?
    猜你喜欢
    • 2021-02-03
    • 1970-01-01
    • 1970-01-01
    • 2016-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多