Multi-tables joining in Cursor - sql-server

I got a table of words to be searched in the database and the table
Parameter
id Name Word
----------------------------------
1 word search c&a
2 word search Beton
3 word search Freiman
4 Anything Null
beside that i have the Procedure SearchAllTable, which is the searching Procedure and for searching the words in the database.
DECLARE #id int
DECLARE #name varchar(100)
DECLARE #word varchar(100)
DECLARE cur CURSOR FOR SELECT Id, word FROM #Parameter WHERE Name = 'word search'
OPEN cur
FETCH NEXT FROM cur INTO #id,#word
WHILE ##FETCH_STATUS = 0 BEGIN
EXEC SearchAllTables #word
FETCH NEXT FROM cur INTO #id, #word
END
CLOSE cur
DEALLOCATE cur
the problem that I got the result in multipule tables and I want them all to be listed in one table without any suppuration.

Insert your results into temporary table, created before cursor cycle
UPDATE
try this UNION the results of multiple stored procedures

Collect your result into a temp table or table variable and get it in a single select outside the cursor. Please try the bellow.
DECLARE #id int
DECLARE #name varchar(100)
DECLARE #word varchar(100)
--Create Result table wrt your SP output
DECLARE #Result TABLE (NAME VARCHAR(16), DATEVAL DATETIME)
DECLARE cur CURSOR FOR SELECT Id, word FROM #Parameter WHERE Name = 'word search'
OPEN cur
FETCH NEXT FROM cur INTO #id,#word
WHILE ##FETCH_STATUS = 0
BEGIN
INSERT INTO #Result
EXEC SearchAllTables #word
FETCH NEXT FROM cur INTO #id, #word
END
CLOSE cur
DEALLOCATE cur
--Selecting result as a single unit
SELECT * FROM #Result

Related

Stored procedure - Only return if rows > 0

I have this stored procedure which executes a lot of SQL queries and returns the results. How do i go about returning only the results from the queries that returns rows?
BEGIN
DECLARE #Query varchar(4000)
DECLARE cur CURSOR FOR SELECT SQLSyntax FROM tblChecks
OPEN cur
FETCH NEXT FROM cur INTO #Query
WHILE ##FETCH_STATUS = 0 BEGIN
EXEC (#Query)
FETCH NEXT FROM cur INTO #Query
END
CLOSE cur
DEALLOCATE cur
END
Please help me...
To avoid returning empty result sets, you have to conditionally run each query. For instance:
declare #query varchar(4000)
declare cur cursor local for
select 'if exists (' + SQLSyntax + ') ' + SQLSyntax from tblChecks
open cur
fetch next from cur into #query
while ##fetch_status = 0
begin
exec(#query)
fetch next from cur into #query
end
close cur
deallocate cur
Or, if every result set is identical, you could create a temp table first, and then insert all values into the temp table, and then do a single select statement at the end from the temp table:
create #temp (field1 type null, field2 type null, field3 type null)
declare #query varchar(4000)
declare cur cursor local for
select 'insert into #temp ' + SQLSyntax from tblChecks
open cur
fetch next from cur into #query
while ##fetch_status = 0
begin
exec(#query)
fetch next from cur into #query
end
close cur
deallocate cur
select * from #temp
drop table #temp
If possible, the 2nd option is better, because it will only run each query one time. The 1st option will run each query twice (that returns data), once to test if there are any results and once to return the data. This is not efficient! Hopefully all queries return the same fields in the results and you can use the 2nd option.
You can also execute and evaluate the results using the If exists strategy.
IF EXISTS(exec(#query))
BEGIN
exec(#query)
END

Truncate selected tables in SQL Server

How to truncate selective tables in SQL Server 2008,
I have a list of tables which may be excluded during truncate process.
Can anybody guide me?
You can simply run TRUNCATE TABLE yourTableName. If you have a list you can run the following:
CREATE TABLE #truncateTables(name nvarchar(255))
INSERT INTO #truncateTables(name) VALUES(N'dbo.yourTable1'),(N'dbo.yourTable2')
DECLARE cur CURSOR FOR
SELECT name FROM #truncateTables
OPEN cur
DECLARE #sql nvarchar(max), #tabname nvarchar(255)
FETCH NEXT FROM cur INTO #tabname
WHILE ##FETCH_STATUS = 0 BEGIN
SET #sql = N'TRUNCATE TABLE '+#tabname
BEGIN TRY EXEC(#sql)
END TRY
BEGIN CATCH -- if a foreign key constraint exists
SET #sql = N'DELETE FROM '+#tabname
EXEC(#sql)
END CATCH
FETCH NEXT FROM cur INTO #tabname
END
CLOSE cur
DEALLOCATE cur
DROP TABLE #truncateTables

Print statement not executing while using in cursor in SQL Server 2012

I am using SQL Server 2012: This is the query using cursors.
create table test(id varchar(10), name varchar(10))
insert into test values('1','a'),('2','b'),('3','c')
declare #id varchar(10)
declare #name varchar(10)
declare cur cursor for
select id, name
from test
open cur
if ##CURSOR_ROWS > 0
begin
fetch next from cur into #id, #name
while ##FETCH_STATUS=0
begin
print 'test'
print #id+','+#name
fetch next from cur into #id,#name
end
end
close cur
deallocate cur
But in the result set it doesn't display results, but gets successfully executed.
Expected result
1,a
2,b
3,c
##CURSOR_ROWS is returning -1 that's why it's not printing.
Try this:
declare #id varchar(10)
declare #name varchar(10)
declare cur cursor for
select id, name from test
open cur
fetch next from cur into #id, #name
while ##FETCH_STATUS = 0
begin
print #id+','+#name
fetch next from cur into #id,#name
end
close cur
deallocate cur
Read more about ##CURSOR_ROWS.

SQL Server stored procedure to empty specific tables

I have a stored procedure which is supposed to truncate specific tables based on their names.
Tables which do not have "A" as the first character in their names must be truncated.
The problem is that this code doesn't work! Please help
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[return_data]
#DBName varchar(100)
AS
declare #i int, #tc int
set #i = 1
DECLARE #sql NVARCHAR(100)
SET #sql = 'USE ' + QUOTENAME(#DBName) + '
DECLARE cur CURSOR FOR SELECT TABLE_NAME FROM information_schema.tables
'
EXECUTE(#sql)
OPEN cur
declare #tbl_name nvarchar(100)
declare #first_char char(1)
FETCH NEXT FROM cur INTO #tbl_name
WHILE ##FETCH_STATUS = 0 BEGIN
set #first_char = SUBSTRING(#tbl_name, 0, 1)
set #sql = 'DELETE FROM ' + QUOTENAME(#tbl_name)
if (#first_char != 'A')
begin
EXECUTE(#sql)
end
FETCH NEXT FROM cur INTO #tbl_name
END
CLOSE cur
DEALLOCATE cur
return
The problem is with the SUBSTRING function. The starting position is a 1-based ordinal, not 0-based. Try
SUBSTRING(#tbl_name, 1, 1)
or
LEFT(#tbl_name, 1)
Also, I suggest you make it a habit of schema-qualifying table names to avoid ambiguity.

how to call procedure in procedure in sql server

i have one procedure name Randomoutlet and i want to call that procedure via other procedure as code below
ALTER procedure [dbo].[MainSchedule]
as
begin
DECLARE #sup table (supervisorId int)
INSERT INTO #sup SELECT DISTINCT SupervisorId FROM CallPlan .dbo .CallPlanSchedule WHERE MONTH (scheduledate)= MONTH (GETDATE ()) and YEAR (ScheduleDate )= YEAR(GETDATE())
DECLARE CUR CURSOR FORWARD_ONLY FOR SELECT * FROM #sup
DECLARE #suptem int
OPEN CUR
FETCH NEXT FROM CUR INTO #suptem
WHILE ##FETCH_STATUS =0
BEGIN
EXEC [dbo].[randomOutlet] #suptem
FETCH NEXT FROM CUR INTO #suptem
END
CLOSE CUR
DEALLOCATE CUR
end
when i save MainSchedule it's show message "The module 'MainSchedule' depends on the missing object 'dbo.randomOutlet'. The module will still be created; however, it cannot run successfully until the object exists.
"
and when i run this procedure it's appear error "Msg 2812, Level 16, State 62, Procedure MainSchedule, Line 15
Could not find stored procedure 'dbo.randomOutlet'."
please help me solve this problem thank in advance
I tried the following and got everything running fine.
CREATE procedure CALL_PROC --'abc'
#var varchar(100)
as
begin
declare #sup table (item int)
insert into #sup select 1 union select 2
DECLARE CUR CURSOR FORWARD_ONLY FOR SELECT * FROM #sup
DECLARE #var1 int
OPEN CUR
FETCH NEXT FROM CUR INTO #var1
WHILE ##FETCH_STATUS =0
BEGIN
EXEC dbo.call_me #var1
FETCH NEXT FROM CUR INTO #var1
END
CLOSE CUR
DEALLOCATE CUR
end
go
CREATE PROCEDURE [dbo].[CALL_ME]
#VAR VARCHAR(100)
AS
if OBJECT_ID('tempdb..#temp') is not null
begin
insert into #temp select #VAR
end
else
select #var value into #temp
select * from #temp
go
Please check if you have created the objects on the same DB or not.

Resources