Using Microsoft SQL 2008
I have a loop that should grab data from each row but it only seems to be grabbing the last row.
The table is
CREATE TABLE [dbo].[TEST](
[PK] [int] NULL,
[ITEMS] [varchar](50) NULL
) ON [PRIMARY]
insert into dbo.test (pk, items) values (1, '1111')
insert into dbo.test (pk, items) values (2, '2222')
insert into dbo.test (pk, items) values (3, '3333')
insert into dbo.test (pk, items) values (4, '4444')
I am trying to loop through it and grab the items per row for an insert but I am only getting the last row:
-- Get the number of rows in the looping table
DECLARE @RowCount INT
SET @RowCount = (SELECT COUNT(ITEMS) FROM dbo.TEST)
Print @ROWCOUNT
-- Declare an iterator
DECLARE @I INT
-- Initialize the iterator
SET @I = 1
--Loop through the rows of a table
WHILE (@I <= @RowCount)
BEGIN
Declare @Name varchar(100)
SELECT @Name = Lower(ITEMS) FROM dbo.TEST
PRINT 'Row No = ' + CONVERT(VARCHAR(2), @I)
Print @Name
-- Increment the iterator
SET @I = @I + 1
END
The results I am getting are:
4
Row No = 1
4444
Row No = 2
4444
Row No = 3
4444
Row No = 4
Seems simple enough but I can’t find any information on why this is happening and/or get my head around the loop and why it is not working.
Thank you,
Heather
As Philip Kelley noted
SELECT @Name = Lower(ITEMS) FROM dbo.TESTwill always give you the last item in the result. So his solution (addingWHERE PK = @I) will work if the PKs in the table start with 1 and are sequential. If either those conditions don’t hold true then you’ll have to do somthing like this.Although in all honestly you’re probably better of with
FAST_FORWARDcursor since you’ve lost the set-based operations battle already.See this data.se query for a working example (note I added another item
6,'6666')