I m trying to search database values through the views.
I m stuck at the below error.
USE AdventureWorks
GO
--EXEC Customer.sp_FindInViews Stephen, Sales
ALTER PROCEDURE Customer.sp_FindInViews @stringToFind VARCHAR(100), @schema sysname
AS
SET NOCOUNT ON
DECLARE
@ViewName AS nVarChar(128)
, @TmpQuery AS nVarChar(500)
, @Out3 as int
, @sqlCommand VARCHAR(8000)
, @where VARCHAR(8000)
, @columnName sysname
, @cursor VARCHAR(8000)
DECLARE Outer_Cursor CURSOR FOR
SELECT schema_name(schema_id)+'.'+name as "View_Name",schema_id FROM [sys].[all_views]
where schema_id in (@schema)
OPEN Cur_Views
FETCH NEXT FROM Cur_Views INTO @ViewName
WHILE @@Fetch_Status = 0
BEGIN
SET @sqlCommand = 'SELECT * FROM ' + @ViewName + ' WHERE'
SET @where = ''
DECLARE col_cursor CURSOR FOR
SELECT syscolumns.name FROM sys.sysobjects "sysobjects"
INNER JOIN sys.syscolumns "syscolumns"
on syscolumns.id = sysobjects.id
WHERE (sysobjects.type = 'V' and SCHEMA_NAME(sysobjects.uid) + '.' +sysobjects.name = @ViewName)
OPEN col_cursor
FETCH NEXT FROM col_cursor INTO @columnName
WHILE @@FETCH_STATUS = 0
BEGIN
IF @where <> ''
SET @where = @where + ' OR'
---------------------------------------------------------------------------
SET @where = @where + ' ' + @columnName + ' LIKE ''' + @stringToFind + ''''
SET @sqlCommand = @sqlCommand + @where
CREATE TABLE #Data (var varchar)
SELECT @TmpQuery = @sqlCommand
INSERT #Data exec (@TmpQuery)
SELECT @Out3 = var from #Data
PRINT @Out3
DROP TABLE #Data
FETCH NEXT FROM col_cursor INTO @columnName
END
CLOSE col_cursor
DEALLOCATE col_cursor
CLOSE Outer_Cursor
DEALLOCATE Outer_Cursor
END
GO
The code compiles , but it does give the error when executed as below :
EXEC Customer.sp_FindInViews Stephen, Sales
Msg 16915, Level 16, State 1, Procedure sp_FindInViews, Line 19
A cursor with the name 'Outer_Cursor' already exists.
Msg 16905, Level 16, State 1, Procedure sp_FindInViews, Line 22
The cursor is already open.
Msg 16924, Level 16, State 1, Procedure sp_FindInViews, Line 23
Cursorfetch: The number of variables declared in the INTO list must match that of selected columns.
I m not sure , why I m getting this error. I feel i m handling them. Any input on this , would be helpful.
Thanks.
Looks to me that you’ve changed cursor names. You start by declaring Outer_Cursor then open a cursor called Cur_Views.
Also when you fetch from the cursor you are only putting the cursor values in to 1 variable, in the cursor declaration you list 2 fields (View_Name and schema_id).
The “cursor is already open” errors occur when you run the procedure a second time becuase the original cursors are still open (as the first attempt errored before being able to close them).