Foreach vs Cursor

So what if we have a list and we want to go through it an item at a time?

For fun let’s do this first in PowerShell and then replicate the results using a T-SQL cursor.

Powershell – Foreach

Code:

$GetColor = @("Blue","White","Red","Cyan","Yellow") 

foreach ($ColorProperty in $GetColor) {                            

                                write-host $ColorProperty

                                       } #end foreach

Output:

Blue
White
Red
Cyan
Yellow

T-SQL – Cursor

This being sql, let’s start with a database:

database

table

Code:

declare @ColorProperty char(10)
declare @GetColor cursor

set @GetColor = cursor for select Color FROM test_db1.dbo.table1

open @GetColor
fetch next from @GetColor into @ColorProperty

while @@FETCH_STATUS = 0
Begin

Print @ColorProperty
fetch next from @GetColor into @ColorProperty

End

close @GetColor
deallocate @GetColor

Output:

Blue      
White     
Red       
Cyan      
Yellow
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s