Cursor not working in stored procedure - sql

I am using cursor in ms sql server
DECLARE #LineOfAuthoritySubString varchar(100);
declare #tbProductId int;
declare #tbLineOfAuthorityId int;
DECLARE #MyCursor CURSOR
SET #MyCursor = CURSOR FAST_FORWARD
FOR
Select TempLineOfAuthority FROM #tbTempLineOfAuthority
OPEN #MyCursor
FETCH NEXT FROM #MyCursor
INTO #LineOfAuthoritySubString
WHILE ##FETCH_STATUS = 0
BEGIN
Set #tbLineOfAuthorityId = (Select LineOfAuthority
from tbLineOfAuthority where LineOfAuthorityX = #LineOfAuthorityNameSubString);
INSERT INTO tbProductLineOfAuthority(ProductId, LineOfAuthortyId)
VALUES(#tbProductId, #tbLineOfAuthorityId);
FETCH NEXT FROM #MyCursor
INTO #LineOfAuthoritySubString
END
CLOSE #MyCursor
DEALLOCATE #MyCursor
It's not working. It is assigning null value to the variable #tbLineOfAuthorityId.

You are inserting cursor value in #LineOfAuthoritySubString and in where condition #LineOfAuthorityNameSubString variable is used
Both variable name is mismatched.
FETCH NEXT FROM #MyCursor INTO #LineOfAuthoritySubString
IN above you are fetching value in variable #LineOfAuthoritySubString .
Set #tbLineOfAuthorityId = (Select LineOfAuthority from tbLineOfAuthority where LineOfAuthorityX = #LineOfAuthorityNameSubString);
But when you are selecting from table tbLineOfAuthority, observe the variable you are using in where query.
It should be #LineOfAuthoritySubString and not #LineOfAuthorityNameSubString
pleae try below edited query if it works.
DECLARE #LineOfAuthoritySubString varchar(100);
declare #tbProductId int;
declare #tbLineOfAuthorityId int;
DECLARE #MyCursor CURSOR
SET #MyCursor = CURSOR FAST_FORWARD
FOR
Select TempLineOfAuthority FROM #tbTempLineOfAuthority
OPEN #MyCursor
FETCH NEXT FROM #MyCursor
INTO #LineOfAuthoritySubString
WHILE ##FETCH_STATUS = 0
BEGIN
Set #tbLineOfAuthorityId = (Select LineOfAuthority
from tbLineOfAuthority where LineOfAuthorityX = #LineOfAuthoritySubString);
INSERT INTO tbProductLineOfAuthority(ProductId, LineOfAuthortyId)
VALUES(#tbProductId, #tbLineOfAuthorityId);
FETCH NEXT FROM #MyCursor
INTO #LineOfAuthoritySubString
END
CLOSE #MyCursor
DEALLOCATE #MyCursor

Related

Delete multiple records from table through cursor in sql server

there are number of test IP's which I would like to remove through system defined sp
exec sp_delete_firewall_rule from sys.firewall_rules table in sql server
I am using below cursor but its not working
declare #name nvarchar(max)
declare cur CURSOR LOCAL for
select #name from sys.firewall_rules where [name] like '%TestIP%'
open cur
fetch next from cur into #name
while ##FETCH_STATUS = 0 BEGIN
exec sp_delete_firewall_rule #name
fetch next from cur into #name
END
close cur
deallocate cur
It worked for me, you just need to change a couple of things in your code.
In the select list include the table ColumnName [name] instead of variable. You did not pass any value to the variable so this gives a NULL result.
Include SP parameter while executing exec sp_delete_firewall_rule #name = #name1;
I have these IP’s in my firewall rules:
With the below code I am deleting the IP’s which has a name like TestIP1.
DECLARE #name1 nvarchar(128);
DECLARE MyCursor CURSOR FOR
SELECT [name] from sys.firewall_rules where [name] like '%TestIP1%';
OPEN MyCursor;
FETCH FROM MyCursor into #name1
WHILE ##FETCH_STATUS = 0 BEGIN
EXEC sp_delete_firewall_rule #name = #name1 ;
FETCH next from MyCursor into #name1
END
CLOSE MyCursor;
DEALLOCATE MyCursor;
GO
Now the result shows only 1 IP which is not included in the above delete list.

Is there a way to do bitwise OR on any column using single query?

I am trying to find is there a way to calculate the bitwise OR of a column of a table using a single query. I can achieve the same using cursor
Declare #orValue int;
Declare #fieldValue int;
set #orValue = 0;
DECLARE my_cursor CURSOR FOR
SELECT MyField
FROM MyTable
WHERE SomeColumnValue=123
OPEN my_cursor
FETCH NEXT FROM my_cursor
INTO #fieldValue
WHILE ##FETCH_STATUS = 0
BEGIN
set #orValue = #orValue | #fieldValue;
FETCH NEXT FROM my_cursor INTO #fieldValue
END
CLOSE my_cursor;
DEALLOCATE my_cursor;
print #orValue;
Have done some google but didn't find any solution.
DECLARE #orv INT = 0;
SELECT #orv=#orv|MyField
FROM MyTable
WHERE SomeColumnValue=123;

How do I loop through the results of a SELECT statement sql and use the result for stored procedure?

I want to use the result of a select query into a stored procedure by using cursor but it doesn't work.
Here is my code:
DECLARE #NumberPhone varchar(50)
DECLARE CUR CURSOR STATIC FOR
SELECT MobilePhone
FROM info_client
OPEN CUR
FETCH NEXT FROM CUR INTO #NumberPhone
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #return_value int, #idCli int, #sCode varchar(2)
EXEC #return_value = StoredP_Test
#sLignePhone = #NumberPhone,
#sIMEI ='00000000000000000',
#idCli = #idCli OUTPUT,
#sCode = #sCode OUTPUT
SELECT #idCli as N'#idCli',
#sCode as N'#sCode'
FETCH NEXT FROM CUR INTO #NumberPhone
SELECT 'Return Value' = #return_value
END
CLOSE CUR
DEALLOCATE CUR
This code duplicate the same result as the number of line of the select query.
Your code has an initial fetch of
FETCH NEXT FROM CUR INTO #NumberPhone
Your code has a fetch next inside the loop
FETCH NEXT FROM CUR INTO #sLigneAssValue
Didn't you want to fetch next into the #NumberPhone variable?
The #NumberPhone variable will never change.

Return one table from cursor

Please see the code below:
DECLARE #ID int
DECLARE #errorflag int
DECLARE Warning_Cursor CURSOR FOR
SELECT TOP 3 ID FROM Warnings
SET #errorflag = #errorflag + ##Error
OPEN Warning_cursor
SET #errorflag = #errorflag + ##Error
FETCH NEXT FROM Warning_cursor INTO #ID
WHILE ##FETCH_STATUS = 0
begin
SELECT #ID
FETCH NEXT FROM Warning_cursor INTO #ID
END
CLOSE Warning_cursor
DEALLOCATE Warning_cursor
The cursor returns three tables with one row each. How can I return one table with three rows?
Why don't you just do,
SELECT TOP 3 ID FROM Warnings
More generally, if you are using a cursor, you are probably doing it wrong.
If you really have to use a cursor for some reason that is not part of the question. You could do
DECLARE #Id int;
DECLARE #Ids TABLE (Id Int);
DECLARE Warning_Cursor CURSOR FOR SELECT TOP 3 ID FROM Warnings;
OPEN Warning_cursor;
FETCH NEXT FROM Warning_cursor INTO #Id;
WHILE ##FETCH_STATUS = 0 BEGIN
INSERT #Ids SELECT #Id;
FETCH NEXT FROM Warning_cursor INTO #Id;
END
CLOSE Warning_cursor;
DEALLOCATE Warning_cursor;
SELECT Id FROM #Ids;
The answer was to create a temporary table as follows:
DECLARE #ID int
DECLARE #errorflag int
DECLARE #CONCATRESULT TABLE (ID INT)
DECLARE Warning_Cursor CURSOR FOR
SELECT TOP 3 ID FROM Warnings
SET #errorflag = #errorflag + ##Error
OPEN Warning_cursor
SET #errorflag = #errorflag + ##Error
FETCH NEXT FROM Warning_cursor INTO #ID
WHILE ##FETCH_STATUS = 0
begin
INSERT into #CONCATRESULT (ID) VALUES (#ID)
FETCH NEXT FROM Warning_cursor INTO #ID
END
CLOSE Warning_cursor
DEALLOCATE Warning_cursor
select id from #CONCATRESULT

Get Multiple Values in SQL Server Cursor

I have a cursor containing several columns from the row it brings back that I would like to process at once. I notice most of the examples I've seeing on how to use cursors show them assigning a particular column from the cursor to a scalar value one at a time, then moving to the next row,
e.g.
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO #name
WHILE ##FETCH_STATUS = 0
BEGIN
--Do Stuff with #name scalar value, then get next row from cursor
FETCH NEXT FROM db_cursor INTO #name
END
What I want to know is if it's possible to do something like the following:
OPEN db_cursor
FETCH NEXT FROM db_cursor;
WHILE ##FETCH_STATUS = 0
BEGIN
SET #myName = db_cursor.name;
SET #myAge = db_cursor.age;
SET #myFavoriteColor = db_cursor.favoriteColor;
--Do stuff with scalar values
FETCH NEXT FROM db_cursor;
END
Help is always appreciated.
This should work:
DECLARE db_cursor CURSOR FOR SELECT name, age, color FROM table;
DECLARE #myName VARCHAR(256);
DECLARE #myAge INT;
DECLARE #myFavoriteColor VARCHAR(40);
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO #myName, #myAge, #myFavoriteColor;
WHILE ##FETCH_STATUS = 0
BEGIN
--Do stuff with scalar values
FETCH NEXT FROM db_cursor INTO #myName, #myAge, #myFavoriteColor;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;
Do not use ##fetch_status - this will return status from the last cursor in the current connection. Use the example below:
declare #sqCur cursor;
declare #data varchar(1000);
declare #i int = 0, #lastNum int, #rowNum int;
set #sqCur = cursor local static read_only for
select
row_number() over (order by(select null)) as RowNum
,Data -- you fields
from YourIntTable
open #cur
begin try
fetch last from #cur into #lastNum, #data
fetch absolute 1 from #cur into #rowNum, #data --start from the beginning and get first value
while #i < #lastNum
begin
set #i += 1
--Do your job here
print #data
fetch next from #cur into #rowNum, #data
end
end try
begin catch
close #cur --|
deallocate #cur --|-remove this 3 lines if you do not throw
;throw --|
end catch
close #cur
deallocate #cur