Showing posts with label sql server loop through records. Show all posts
Showing posts with label sql server loop through records. Show all posts

Sunday, 28 August 2011

SQL Loop through records and replace


use DB_Name
DECLARE @var_1 as nvarchar(300)
DECLARE @var_2 as int --DECLARE @VariableName as Variable DataType
                                              --You can DECLARE many variable seperated by comma
                                              --to add another variable to the previous declaration use this example
                                              --,
                                              --@Variable2 as char

                             
DECLARE cursor_ CURSOR FOR   --declare the cursor
SELECT    primary_key_column_name , column2         --write a correct select statmen
FROM dbo.TableName

OPEN cursor_      --Open the cursor
FETCH NEXT FROM cursor_ INTO @var_1, @var_2  -- filling the variables using the cursor
WHILE (@@FETCH_STATUS = 0)        --Looping through the cursor
  BEGIN                             --Write you code here to do what you want


if(@var_2='null' or @var_2='NULL' OR @var_2='Null')

   UPDATE dbo.Channels SET var_2=column_name_to_be_replaced_with
   WHERE primary_key_column_name=@var_1

   FETCH NEXT FROM cursor_ INTO @chanID_, @chanName_Ar_ --To move the cursor to the next row
  END
  CLOSE cursor_                       --You have to close the cursor
  DEALLOCATE cursor_                  --You have to free the memory