【问题标题】:How to delete all the records in a declared table inside a storedprocedure如何删除存储过程中声明的表中的所有记录
【发布时间】:2012-08-24 19:33:40
【问题描述】:

我正在创建一个电子邮件队列来处理电子邮件发送。我从该队列中获取 X 条记录并根据记录的类型字段发送电子邮件。

为此,我在存储过程中声明了一个表。当获取 X 条记录时,我将 EmailQ 表 中的记录状态设置为处理中。但是在发送 现在声明的表中的 X 条记录后,必须删除

为此,我可以使用 Delete 但有这个 TRUNCATE 删除表中的所有记录。但是声明的表还没有标识为表。

WHILE EXISTS ( SELECT * FROM emailQ WHERE Status != 3)
BEGIN
  CREATE PROCEDURE [dbo].[SendMails]
  DECLARE @Temp TABLE (......)
  --Declare all the necessary variables

  INSERT INTO @Temp SELECT TOP 10
  WITH (UPDLOCK, HOLDLOCK)

  --Update the email queue table status of selected set of records in to the @Temp

  DECLARE  dataSet CURSOR FORWARD_ONLY FOR (SELECT.......  FROM @Temp)
  OPEN dataSet
  FETCH NEXT FROM dataSet INTO...

  WHILE @@FETCH_STATUS = 0
  BEGIN
    --send mails acordingly
  END

  CLOSE dataSet
  DEALLOCATE dataSet

  --Update the email queue table status of completed set of records in to the @Temp

  WAITFOR DELAY...
  TRUNCATE @Temp// This is where this Temp table is not identified as a table(It says     "Incorrect sintax... Expecting a table")

 END

从这个声明的表中删除记录的最合适的方法是什么。 我也很感谢 cmets 在我处理邮件发送的方式上。

谢谢。

【问题讨论】:

  • 你试过“从@Temp删除”吗?
  • 它可以工作,谢谢 aarghh.... 你知道为什么这个 Truncate 不能在这个声明的表上工作吗?

标签: sql sql-server sql-server-2008-r2 temp-tables


【解决方案1】:

你应该用删除来做

DELETE FROM @Temp

查看相关问题

SQL Server, temporary tables with truncate vs table variable with delete

更多关于截断和临时表

TRUNCATE TABLE

Should I use a #temp table or a @table variable?

更新:

截断表不适用于声明的表变量。您应该改用 #Temp 表或删除行而不是 trancating。查看相关问题了解更多信息。

更新 2:

马丁·史密斯的回答很好

What's the difference between a temp table and table variable in SQL Server?

【讨论】:

  • 哦,我的错,我真的必须检查我的视力。(粗心)非常感谢 hgulyan
  • 有效吗? TRUNCATE TABLE @Temp 显示不正确的语法
  • 你说得对,它不起作用。我认为他是通过 delete 做到的。
【解决方案2】:

如下创建表格..

DECLARE @tempTable table(BatchId int, BatchInputOutputType NVARCHAR(128));

使用以下查询删除临时表

DELETE from @tempTable;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多