Delete multiple records from table through cursor in sql server - sql

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.

Related

Cursor within a cursor for database dependent permissions

It would seem that my code should work, however testing indicates that all the results from the inner cursor are based on the current database at execution of the script and not dependent upon the USE statement within the script.
WHAT DID I FORGET?
DECLARE #Debug BIT = 1
DECLARE #newgrp VARCHAR(100) = 'ChangeTrakingViewableRole'
DECLARE #obj VARCHAR(100)
DECLARE #tsql VARCHAR(900)
DECLARE #tsql2 VARCHAR(900)
DECLARE #msg VARCHAR(900)
DECLARE #SchName VARCHAR(55)
DECLARE #TblName sysname
IF #Debug = 'TRUE' PRINT 'Debuging ON'
IF COALESCE(#newgrp,'') = ''
BEGIN
PRINT 'There was no DatabaseRole, User or Group Specified to take the place of the Public Role'
SET NOEXEC ON
END
ELSE
BEGIN
DECLARE DbCursor CURSOR FOR
SELECT 'USE '+DB_NAME(database_id) FROM sys.change_tracking_databases
OPEN DbCursor
FETCH NEXT FROM DbCursor INTO #obj
WHILE ##Fetch_Status = 0
BEGIN
SET #tsql2 = #obj+'; '
RAISERROR (#tsql2, 0, 1) WITH NOWAIT
EXEC sp_sqlexec #tsql2
-----------Commands within this next section are all database dependent
BEGIN --GRANT [VIEW CHANGE TRACKING] TO Change Tracking Enabled Tables
IF NOT EXISTS (SELECT name FROM sys.database_principals where name = #newgrp)
BEGIN
SET #tsql = N'CREATE ROLE '+#newgrp+' AUTHORIZATION [dbo]'
IF #Debug = 'TRUE'
BEGIN
SET #Msg = #tsql
RAISERROR (#Msg, 0, 1) WITH NOWAIT
END
ELSE
BEGIN
EXEC sp_sqlexec #tsql
END
END
DECLARE TblCursor CURSOR FOR
SELECT sch.name, tbl.name
FROM sys.change_tracking_tables chg
JOIN sys.tables tbl ON chg.object_id=tbl.object_id
JOIN sys.schemas sch ON tbl.schema_id=sch.schema_id
ORDER BY sch.name, tbl.name
OPEN TblCursor
FETCH NEXT FROM TblCursor INTO #SchName,#TblName
WHILE ##FETCH_STATUS = 0
BEGIN
SET #tsql = 'GRANT VIEW CHANGE TRACKING ON ['+#SchName+'].['+#TblName+'] TO '+#newgrp
IF #Debug = 'TRUE'
BEGIN
SET #Msg = #tsql
RAISERROR (#Msg, 0, 1) WITH NOWAIT
END
ELSE
BEGIN
EXEC sp_sqlexec #tsql
END
FETCH NEXT FROM TblCursor INTO #SchName,#TblName
END
CLOSE TblCursor
DEALLOCATE TblCursor
END
FETCH NEXT FROM DbCursor INTO #obj
END
CLOSE DbCursor
DEALLOCATE DbCursor
END
The USE statements in your outer cursor are not doing anything for the statements generated aftwerward because they're being executed independently. When your outer cursor executes the USE it is just valid for the scope of the first EXEC sp_sqlexec call; it doesn't change the database context of the overall script. The context under which the rest of your script runs is still that of the overall script, meaning those statements will get run in the current database every time.
Bascially, you need to change this to generate a single script with the entirety of what you want to execute within the dynamic db context top to bottom, with the USE at the top, and then execute that whole thing in a single call to EXEC or sp_executesql.

How to write a stored procedure, so that it will run the last column and save that in a table?

I have a table which has last column is the code. The table looks like below:
Rule_ID Simple_English_Description Source_Attribute Dependent_Attribute View text
-------------------------------------------------------------------------------------------
39 Material description Mandatory for all Material types Material Description Basic Data
Code:
INSERT INTO GDQ_PRODUCT_ERROR_TABLE
SELECT
'39' as RULE_ID,
vw.MATNR, VW.REGION_CODE, VW.COUNTRY_CODE, VW.[CLUSTER_CODE],
VW.[COMMON_COUNTRY],
'MATERIAL DESCRIPTION' as SRC_ATTR,
VW.MAKTX AS SOURCE_VALUE,
'' AS WERKS,
VW.MTART, VW.MAKTX, VW.NUMTP, VW.EAN11, VW.MEINS, VW.MSTAE, VW.PRDHA,
CASE
WHEN (vw.MAKTX IS NULL OR RTRIM(LTRIM(vw.MAKTX)) = ''
THEN 'I'
ELSE 'V'
END as DQ_INVALID
FROM
T_U2K2_ECC_MAKT_GDQ_ACTIVE vw;
How to write the stored procedure so that it can be a loop and read from the last column and return the output?
I have tried writing a stored procedure but it is not able to select only last column and insert the value into main table.
I have tried below code:
DECLARE #item CHAR(2)
DECLARE item_cursor CURSOR FAST_FORWARD READ_ONLY FOR
SELECT [text] from GDQ_RULE_MSTR_copy
OPEN item_cursor
FETCH NEXT FROM item_cursor INTO #item
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #Query nvarchar(max)
SET #Query = (N'Select [text] FROM GDQ_RULE_MSTR_copy')
EXECUTE sp_executesql #Query
FETCH NEXT FROM item_cursor INTO #item
END
CLOSE item_cursor
DEALLOCATE item_cursor
I have tried this code but here it's executing the text column not the inside value which is the original code in string format I have saved
You are putting Select [text] FROM GDQ_RULE_MSTR_copy in quotes N'' which will actually execute the Select [text] FROM GDQ_RULE_MSTR_copy statement itself when you execute the #Query.
Also, your cursor is putting the value of Text column in a char(2) #item field which will truncate the string to 2 characters.
Try this:
DECLARE #item NVARCHAR(MAX)
DECLARE item_cursor CURSOR FAST_FORWARD READ_ONLY
FOR SELECT [text] from GDQ_RULE_MSTR_copy
OPEN item_cursor
FETCH NEXT FROM item_cursor INTO #item
WHILE ##FETCH_STATUS = 0
BEGIN
EXECUTE sp_executesql #Item
FETCH NEXT FROM item_cursor INTO #item
END
CLOSE item_cursor DEALLOCATE item_cursor

Dynamic Cursor from the procedure argument

I have a procedure that takes an argument. And I want to loop a cursor through the query based on that argument.
For example:
the argument is passed: salary
the cursor should be (select salary from emp) and loop through it.
How should I do that ?
DECLARE #ARGUMENT VARCHAR(50) = 'salary';
DECLARE #CURSOR_BODY VARCHAR(MAX) = '
declare #variable varchar(max)
declare cur cursor for
select '+ #argument + ' from emp
OPEN cur;
FETCH NEXT FROM cur INTO #variable
WHILE ##FETCH_STATUS=0
BEGIN
select #variable
FETCH NEXT FROM cur INTO #variable;
END
CLOSE cur
DEALLOCATE cur'
print #cursor_body
EXEC (#CURSOR_BODY)
Try sth. like this

How to execute the stored procedure from table using cursor? [duplicate]

This question already has an answer here:
How to execute SQL Server Agent Jobs which are listed in SQL Table
(1 answer)
Closed 6 years ago.
I want to execute a stored procedure from the table and if it ran successfully run the next procedure. There are 50 stored procedures in the table and some need to execute daily, some need to execute weekly and monthly.
I have done this but it is not working. Any help or suggestion would be appreciated.
DECLARE #ProcFreq int
DECLARE #ProcName varchar(100)
DECLARE cur CURSOR FOR SELECT ProcFreq, ProcName FROM #temp
OPEN cur
FETCH NEXT FROM cur INTO #ProcFreq, #ProcName
WHILE ##FETCH_STATUS = 0 BEGIN
EXEC #ProcName
FETCH NExT FROM cur INTO #ProcFreq, #ProcName
END
CLOSE cur
DEALLOCATE cur
DECLARE #ProcFreq int
DECLARE #ProcName varchar(100),
DECLARE #Sql nvarchar(100)
DECLARE cur CURSOR FOR SELECT ProcFreq, ProcName FROM #temp
OPEN cur
FETCH NEXT FROM cur INTO #ProcFreq, #ProcName
WHILE ##FETCH_STATUS = 0
BEGIN
SET #Sql = 'EXEC ' + #ProcName
exec sp_executesql #Sql
FETCH NExT FROM cur INTO #ProcFreq, #ProcName
END
CLOSE cur
DEALLOCATE cur

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.