【问题标题】:Concatenating variable with sproc in temp table insert在临时表插入中将变量与 sproc 连接起来
【发布时间】:2014-04-29 15:10:02
【问题描述】:

我目前有一个查询,它根据前一个查询的结果在临时表中运行 n 次插入。放入临时表的结果来自存储过程。

我还想将一个正在使用的变量连同这些信息一起插入到表中(但未在存储过程中使用)。例子是这样的:

--somewhere up top
Declare @userID int --This is used to get info before the important part
Declare @someOtherID int --This is passed into the sproc

--Some stuff happens here that is unrelated to question

--Important part
while (@@rowcount > 0)
begin
  insert @tmp2 exec spThisSprocDoesntContainOrCareAboutUserID @someOtherID
  delete from @tmp where [someID]=@someOtherID
  select top 1 @id=[id], @someOtherID=[someID] from @tmp
end

SELECT * FROM @tmp2

我还想做的是在@tmp2 的每一行中插入上一节中使用的用户ID。类似的东西

insert @tmp2 @userID + exec spThisSprocDoesntContainOrCareAboutUserID @someOtherID

显然,这行不通。然而,这是我想要做的事情的总体思路。

有人对这个有什么建议吗?

(请注意,我不希望修改存储过程/制作一个类似的存储过程,以便也将该变量传入,如果我能提供帮助,将其传递回结果。并非不可能,只是不想这样做)

【问题讨论】:

  • 为什么要封装在存储过程中?如果它被封装在用户定义的函数中,那么您将拥有更大的灵活性(加入结果、修改它们、过滤它们等)。存储过程仍然可以调用 udf 以实现向后兼容性等。

标签: sql tsql stored-procedures temp-tables


【解决方案1】:

你可以通过一个额外的步骤来做到这一点(正如你提到的,在 sp 中没有任何修改)

insert @tmp3 exec spThisSprocDoesntContainOrCareAboutUserID @someOtherID
insert @tmp2 Select @userId, field1, field2 from @temp3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-26
    • 1970-01-01
    • 1970-01-01
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多