During investigation of a bug in our project I came across some strange to me behaviour. Check the code:
--CREATE TYPE dbo.test AS TABLE(DocumentVersionId INT, ResourceId INT, Deadline DATE)
DECLARE @documents dbo.test
DECLARE @resourceId INT
INSERT INTO @documents(DocumentVersionId, ResourceId, Deadline)
SELECT * FROM (VALUES(1, 1, GETDATE()),(2, 2, GETDATE()),(3, 3, GETDATE())) T(A, B, C)
DECLARE mails CURSOR FAST_FORWARD FOR
SELECT DISTINCT ResourceId
FROM @documents
OPEN mails
FETCH NEXT FROM mails INTO @resourceId
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @docs dbo.test
--DELETE FROM @docs
INSERT INTO @docs(DocumentVersionId, Deadline)
SELECT DocumentVersionId, Deadline
FROM @documents
WHERE ResourceId = @resourceId
SELECT * FROM @docs
FETCH NEXT FROM mails INTO @resourceId
END
CLOSE mails
DEALLOCATE mails
We have procedure that generate mails for data transfered by TVP. Each execution of this procedure must be executed in a loop(cursor) for filtered data. The problem is that, on each loop iteration, the @docs variable contains data from previous iterations even when the variable is recreating each time.
We can delete data from this variable each time, but this is not the behaviour we expect. The question is, why is that happening?
