I make a cursor (MSSQL):
CREATE TABLE #temp
(
DB VARCHAR(50),
Tab VARCHAR(50),
[COUNT] INT
)
DECLARE @db_name NVARCHAR (150)
DECLARE @tab1 NVARCHAR (150)
set @tab1 = 'dbo.test'
DECLARE c_db_names CURSOR FOR
SELECT name
FROM sys.databases
WHERE name like '%KNF%'
OPEN c_db_names
FETCH c_db_names INTO @db_name
WHILE @@Fetch_Status = 0
BEGIN
EXEC('
INSERT INTO #temp
SELECT ''' + @db_name + ''',''' + @tab1 + ''',COUNT(*) FROM ' + @db_name + '.' + @tab1 + '
')
FETCH c_db_names INTO @db_name
END
CLOSE c_db_names
DEALLOCATE c_db_names
SELECT * FROM #temp
DROP TABLE #temp
The cursor counts the number of rows in each database table. If there is no such table there is an error.
(1 row(s) affected)
(1 row(s) affected)
Msg 208, Level 16, State 1, Line 2
Invalid object name 'KNF_C.dbo.test'.
(2 row(s) affected)
What is obvious, because the KNF_C database does not have this table. I would like the entire cursor to handle such an exception.
The expected result:
DB Tab COUNT
KNF_A dbo.test 3
KNF_B dbo.test 7
KNF_C no table
I know I should use syntax for example if exist but i dont know how.
Please help to solve this