SQL Server游标结果显示异常求助:为何游标返回结果不正确?
Hey there! Let's figure out why your cursor is returning incorrect results. Looking at your code snippet, I can spot a major issue that’s almost certainly causing the problem, plus a couple of other things to check:
1. Critical: Missing Lengths on Varchar Variables
When you declare variables like @FullName varchar; and @DeliveryInstructions varchar; without specifying a length, SQL Server defaults them to 1 character long. That means any text fetched into these variables gets truncated to just the first character—so if your FullName is "Jane Smith", @FullName will only hold "J", which makes your results look totally wrong.
Fix this by defining appropriate lengths for your varchar variables, matching the actual data in your tables:
declare @FullName varchar(100); -- Adjust based on the max length of FullName in Application.People declare @DeliveryInstructions varchar(500); -- Match the column's length in Sales.Invoices
2. Incomplete Cursor Fetch Logic
Your code cuts off at open Salescur; f...—make sure you have a full fetch loop to retrieve all rows from the cursor, plus proper cleanup steps. Here’s what the complete logic should look like:
open Salescur; fetch next from Salescur into @FullName, @InvoiceID, @CustomerID, @DeliveryInstructions; -- Loop through all rows in the cursor while @@FETCH_STATUS = 0 begin -- Replace this with your actual logic (e.g., print, process data) print concat(@FullName, ' | Invoice ID: ', @InvoiceID, ' | Customer ID: ', @CustomerID, ' | Instructions: ', @DeliveryInstructions); fetch next from Salescur into @FullName, @InvoiceID, @CustomerID, @DeliveryInstructions; end -- Always clean up your cursor close Salescur; deallocate Salescur;
3. Quick Check: Verify Your Query Outside the Cursor
Before blaming the cursor, run the underlying select query on its own to make sure it returns the correct rows:
select p.FullName, InvoiceID,CustomerID,DeliveryInstructions from Sales.Invoices s inner join Application.People p on s.SalespersonPersonID = p.PersonID where InvoiceDate = '2016-05-31' and s.SalespersonPersonID = 8;
If this query returns the right data, then the cursor issue is definitely tied to the variable lengths or incomplete fetch logic.
Since I can’t see the images you mentioned, if adjusting these fixes still doesn’t resolve the problem, feel free to describe what the incorrect results look like (e.g., truncated text, missing rows, wrong values) and I can help dig deeper!
内容的提问来源于stack exchange,提问作者Jonathan

