简体   繁体   English

如何在 TSQL 中使用 sql 查询结果执行存储过程?

[英]How to execute stored procedure with sql query results in TSQL?

Assuming I have table with tasks called Tasks .假设我有一个名为Tasks的任务表。

I want to delete selected tasks with stored procedure SP_Task_DEL (which deletes tasks).我想使用存储过程SP_Task_DEL (删除任务)删除选定的任务。

This procedure have one parameter @Id (id of task to delete).这个过程有一个参数@Id (要删除的任务的id)。

How to execute this stored procedure many times with all results of query:如何使用所有查询结果多次执行此存储过程:

select id from Tasks where status = 'completed'

? ?

This is done with a cursor.这是通过 cursor 完成的。 Loop over the results and execute the procedure.循环结果并执行该过程。 Do note that this is slow and can most likely be done with one single delete statement.请注意,这很慢,很可能只需一个删除语句即可完成。

DECLARE @id int
DECLARE cur_delete CURSOR LOCAL READ_ONLY
FOR select id 
      from Tasks 
     where status = 'completed'

OPEN cur_delete
FETCH NEXT FROM cur_delete into @id

WHILE @@FETCH_STATUS = 0
  BEGIN
   EXEC SP_Task_DEL @id
   FETCH NEXT FROM cur_delete into @id
  END
CLOSE cur_delete
DEALLOCATE cur_delete

The simplest way to delete all completed tasks is:删除所有已完成任务的最简单方法是:

DELETE Tasks 
where status = 'completed'

If there are more tables to be cleaned out the following pattern needs to be used.如果有更多表要清理,则需要使用以下模式。

BEGIN TRAN
  DELETE SubTasks
  FROM SubTasks st
  JOIN Tasks t (updlock)
    ON st.id = t.id
  WHERE t.status = 'completed' 

  if @@error <> 0 
    begin
      rollback tran
      goto THEEND
    end

  DELETE Tasks 
  where status = 'completed'
COMMIT TRAN
THEEND:

Why not create a different stored procedure that deletes all completed tasks?为什么不创建一个不同的存储过程来删除所有已完成的任务? That would be much more efficient as you can take advantage of the fact that databases are really very efficient at dealing with sets of data rather than looping over individual items.这会更有效率,因为您可以利用数据库在处理数据集而不是循环单个项目方面非常有效的事实。

You could use a cursor for that, like:您可以为此使用 cursor,例如:

declare @id int
declare cur cursor local fast_forward for 
    select id from Tasks where status = 'completed'
open cur
fetch next from cur into @id
while @@fetch_status = 0
    begin
    EXEC dbo.SP_Task_DEL @id
    fetch next from cur into @id
    end
close cur
deallocate cur

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM