drop the bulk table from database - sql

I want to drop bulk table from database whose name is starts with some string.

create table #Temp
(
TableName varchar(50)
)
Insert into #Temp
SELECT NAME FROM SYS.OBJECTS WHERE TYPE='U' NAME LIKE '%'
DECLARE #Name varchar(50)
DECLARE cursorName CURSOR -- Declare cursor
LOCAL SCROLL STATIC
FOR
Select TableName FROM Temp
OPEN cursorName -- open the cursor
FETCH NEXT FROM cursorName
INTO #Name
WHILE ##FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM cursorName
INTO #Name
drop table #Name
END
CLOSE cursorName -- close the cursor
DEALLOCATE cursorName -- Deallocate the cursor
Note : This will work if the table which u are talking abt doesnt have table depedencies .

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.

How to insert records in a existing table using Cursor

Declare Userrole_Cursor Cursor For
Select (User_Role_id,
Pos_entity_Id,
User_role_code,
User_Role_description,
Print_Sequence,
Update_date,
Tx_id,
Add_date,
Add_Username,
Update_Username,
Active_Flag) from User_Role_Tb where pos_entity_id = (pos_entity_id)
Open Cursor
FETCH NEXT FROM UserRole_Cursor into
the above is the Cursor creation i have written, now need to insert in all the mentioned columns in a User_role_tb. please help. this is the first time i am using cursor.
This simple example can help you
-- assume this is your table
create table #tmp (MyDbName varchar(100), MyDbId int, MyStatus int)
-- you need to have a variable for each field.
DECLARE #MyDbName varchar(100)
DECLARE #MyDbId int
DECLARE #MyDbStatus int
DECLARE db_cursor CURSOR FOR
SELECT name, [dbid], [status]
FROM master.dbo.sysdatabases
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO #MyDbName, #MyDbId, #MyDbStatus
WHILE ##FETCH_STATUS = 0
BEGIN
-- insert data into your table using variables
insert into #tmp (MyDbName, MyDbId, MyStatus)
values (#MyDbName, #MyDbId, #MyDbStatus)
-- fetch next row from cursor
FETCH NEXT FROM db_cursor INTO #MyDbName, #MyDbId, #MyDbStatus
END
CLOSE db_cursor
DEALLOCATE db_cursor
-- select from your table to make sure data is there
select * from #tmp

Declare a Cursor From a Table as Variable (In the Select-Statement)

I want to create a SP that have 2 String parameters for 2 table names. In the SP I use dynamic SQL to modify one of the tables, but the other is inside a cursor, and I cant use dynamic SQL after the "FOR"
ALTER PROCEDURE NameProcedure #SourceTable VARCHAR(100),#DestinationTable VARCHAR(100)
AS
BEGIN
DECLARE #AddressSource VARCHAR(100), #AddressDestination VARCHAR(100)
SELECT #AddressSource = '[Test_Toa].[dbo].[' + #SourceTable + ']'
SELECT #AddressDestination = '[Test_Toa].[dbo].[' + #DestinationTable + ']'
--Source Table columns
DECLARE #id int, #idmercado int, #idcadena int, #barcode nvarchar(255),#Complete_P nvarchar(MAX)
DECLARE #Cursor CURSOR
SET #Cursor = CURSOR FOR
--HEREE ITS MY PROBLEM :(!!!!!
SELECT id, idmercado, idcadena, barcode, precios + ',' FROM #AddressSource
OPEN #Cursor
FETCH NEXT
FROM #Cursor INTO #id,#idmercado,#idcadena,#barcode,#Complete_P
WHILE ##FETCH_STATUS = 0
BEGIN
--bla bla code
FETCH NEXT
FROM #Cursor INTO #id,#idmercado,#idcadena,#barcode,#Complete_P
END
CLOSE #Cursor
DEALLOCATE #Cursor
END
I just want to declare a cursor for the table that the user gives
Well, you need to write a dynamic sql statement. Just as an hint. You can copy the values from your given source table into a temp table, generate a cursor on the temp table, iterate through it and deallocate the cursor afterwards and drop the temp table. :-)
Here a short demo code:
DECLARE #sql nvarchar(max), #sourceTable nvarchar(255)
CREATE TABLE dbo.t1(id int, name nvarchar(200))
CREATE TABLE dbo.t2(id int, name nvarchar(200))
SET #sourceTable = N'dbo.t1'
CREATE TABLE #temp(id int, name nvarchar(200))
SET #sql = N'
INSERT INTO #temp(id,name)
SELECT id, name
FROM '+#sourceTable
EXEC(#sql)
DECLARE cur CURSOR FOR
SELECT id, name
FROM #temp
OPEN cur
DECLARE #id int, #name nvarchar(200)
FETCH NEXT FROM cur INTO #id, #name
WHILE ##fetch_status = 0 BEGIN
SELECT #id, #name -- demo output
FETCH NEXT FROM cur INTO #id, #name
END
-- cleanup
CLOSE cur
DEALLOCATE cur
DROP TABLE dbo.t1
DROP TABLE dbo.t2
DROP TABLE #temp
Beware, I just have written this in notepad without any database. But I'm quite sure it does it's job.
This just works if all available variants of #sourceTable have the same column specification. If not, you need to extract the needed columns from information schema and build a more dynamic code.

Append result of stored procedure to earlier executed stored procedure

I have a stored procedure which takes a single parameter containing single value.
I want to pass a collection of values to the procedure one by one and get the combined result into one table . Is this possible ?
Currently I am using cursor to execute procedure in loop but only result from passing first value in the collection is obtained.
declare #clientid varchar(10)
create table #tmpp(secid varchar(10))
insert into #tmpp values(2319)
insert into #tmpp values(2855)
insert into #tmpp values(1303)
declare cur CURSOR LOCAL for
select secid from #tmpp
open cur
fetch next from cur into #seclientid
while ##FETCH_STATUS = 0 BEGIN
exec getReportforclient #clientid
fetch next from cur into #clientid
END
close cur
deallocate cur
drop table #tmpp
If this is too obfuscated / unclear/ silly, can somebody please provide me an alternative ?
Any help is most appreciated . Thanks.
There probably is a way to this without using cursors, but without taking a look at your stored procedure we can't help too much on that. You can create a table (temporary or not) that has the same structure that the results of your sp and insert the results into it. Something like this:
DECLARE #clientid VARCHAR(10)
CREATE TABLE #tmpp(secid VARCHAR(10))
INSERT INTO #tmpp VALUES(2319)
INSERT INTO #tmpp VALUES(2855)
INSERT INTO #tmpp VALUES(1303)
CREATE TABLE #Results(col1 INT, col2.... -- create the table that will hold your
-- results
DECLARE cur CURSOR LOCAL for
SELECT secid
FROM #tmpp
OPEN cur
FETCH NEXT FROM cur INTO #seclientid
WHILE ##FETCH_STATUS = 0
BEGIN
INSERT INTO #Results
exec getReportforclient #clientid
FETCH NEXT FROM cur INTO #clientid
END
CLOSE cur
DEALLOCATE cur
DROP TABLE #tmpp
SELECT *
FROM #Results
Loop without CURSOR
IF OBJECT_ID('tempdb.dbo.#tmpp') IS NOT NULL DROP TABLE #tmpp
CREATE TABLE #tmpp(Clientid varchar(10))
INSERT #tmpp values(2319), (2855), (1303)
IF OBJECT_ID('tempdb.dbo.#Results') IS NOT NULL DROP TABLE #Results
CREATE TABLE #Results(--output columns of procedure)
DECLARE #Clientid int = (SELECT MIN(Clientid) FROM #tmpp)
WHILE (#Clientid IS NOT NULL)
BEGIN
INSERT INTO #Results
EXEC getReportforclient #Clientid
SELECT #Clientid = MIN(Clientid) FROM #tmpp WHERE Clientid > #Clientid
END
Simple example on SQLFiddle

Passing data into nested cursors in TSQL

I have a cursor that gets data and fetches it into #data_table. Then in the while loop I want to pass that #data_table into another cursor (as the table name) to run some more processing. I keep getting a declare #data_table error. How do I fix this?
DECLARE #var_name varchar(50)
DECLARE #data_table varchar(50)
DECLARE #data_value varchar(50)
DECLARE curDiscreteVars CURSOR LOCAL
FOR SELECT DISTINCT v.var_name, v.data_table
FROM dbo.vars v
GROUP BY v.var_name, v.data_table
-- Loop through cursor, translating variable values as needed, and generate counts for each val_code for a variable
OPEN curDiscreteVars
FETCH NEXT FROM curDiscreteVars
INTO #var_name, #data_table
WHILE ##FETCH_STATUS = 0
BEGIN
--loop through all possible data values
DECLARE curValues CURSOR LOCAL
FOR SELECT DISTINCT #var_name
FROM #data_table
OPEN curValues
FETCH NEXT FROM curValues
INTO #data_value
WHILE ##FETCH_STATUS = 0
BEGIN
print #var_name
FETCH NEXT FROM curValues
INTO #data_value
END
CLOSE curValues
DEALLOCATE curValues
FETCH NEXT FROM curDiscreteVars
INTO #var_name, #data_table
END
CLOSE curDiscreteVars
DEALLOCATE curDiscreteVars
For my part, i don't like cursors! For me cursors are evil. The give you locks and such that you don't want.
What i always do is create a temp table with the values (like you normally insert into the cursor) and loop through it with a while loop
like this :
declare #currow int
, #totrow int
create table #tmp_values (id int identity(1, 1), val int)
insert
into #tmp_values
select val
from tableX
set #totrow = ##rowcount
set #currow = 1
while #totrow > 0 and #currow <= #totrow
begin
select #val = val
from #tmp_values
where id = #currow
set #currow = #currow + 1
end
That way you have more control of things and you can re-use the tmp table
I'm not sure I understand what you're talking about doing, but variables cannot be used as table names. Or, really anything that's not a field name. You'll need to use dynamic SQL. That is, assign your SQL string to a variable, an then run EXEC() command.
For example:
DECLARE #sqlcmd varchar(max)
DECLARE #table_name sysname
DECLARE cur_tables FOR
SELECT name FROM sys.tables
OPEN cur_tables
FETCH NEXT FROM cur_tables INTO #table_name
WHILE ##FETCH_STATUS = 0 BEGIN
SET #sqlcmd = 'SELECT TOP 10 * FROM ' + QUOTENAME(#table_name)
EXEC ( #sqlcmd )
FETCH NEXT from cur_tables INTO #table_name
END
CLOSE cur_tables
DEALLOCATE cur_tables
Alternately, if what you mean is that you need a location to store the data that is like a table, then create a temporary tabled for it.