I am creating a email queue to handle email sending. From that queue I’m taking X number of records and send emails according to the type field of the records.
For that I have declared a table inside the stored procedure. When X number of records are taken I am setting the status of the record in the EmailQ table to processing. But after sending X number of records which is now inside the declared table has to be deleted.
For that I can use Delete but there is this TRUNCATE to delete all the records in the table. But the declared table has not identified as a Table.
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
What is the most appropriate way to delete the records from this declared table.
I also appreciate the comments on my way of handling the mail sending.
Thanks.
You should do it with delete
Check related question
SQL Server, temporary tables with truncate vs table variable with delete
More on Truncate and Temp Tables
TRUNCATE TABLE
Should I use a #temp table or a @table variable?
UPDATE:
Truncate table won’t work with declared table variable. You should use #Temp table instead or deleting rows instead of trancating. Check related question for more info.
UPDATE 2:
Great answer by Martin Smith
What’s the difference between a temp table and table variable in SQL Server?