I'm running a query from a server that is linked to another server using cursor. I'm using a list of counties from a different database table, then using that list to interrogate other database tables. The county code from the first list is part of the table name on the other databases. I'm getting an error "table not found" whenever a county from the list is not found on the databases. I want to only pull the data from existing counties and bypass the missing counties.
Is there a way to do that?
I do not have any control on what counties are on the list nor on what tables exists on the database. I just want to process only the existing counties.
Here's my query:
DECLARE
@FIPS CHAR(5)
DECLARE
@STRSQL VARCHAR(8000)
DECLARE
MYCUR CURSORFOR
SELECT
DISTINCT FIPSCODE
FROM
[APEXMAINLIB].MEMBER1.dbo.FIPSCODE
WHERE
FIPSCODE notlike'7%'
ORDER
BY FIPSCODE
OPEN
MYCUR
FETCH
NEXTFROM MYCURINTO @FIPS
WHILE
@@FETCH_STATUS=0
BEGIN
SELECT
@STRSQL ='
INSERT INTO Reporting.dbo.APEX_Cume_Deed (
FIPS, State, County, DataType, [Main Records],
[From Recording Date], [Thru Recording Date],
RecMonth )
SELECT x.FIPS, x.State, x.County, x.DataType,
count(*) as [Main Records],
min(x.[RecordingDate]) as [From Recording Date],
max(x.[RecordingDate]) as [Thru Recording Date],
convert(varchar(7), x.[RecordingDate], 120) as RecMonth
from (
SELECT F5 as FIPS
, F4 as [State]
, upper(F3) as [County]
,''DEED'' as [DataType]
,CONVERT(date, F6) AS [RecordingDate]
FROM [APEXMAINLIB].STX'
+LEFT(@FIPS,2)+'.dbo'+'.D_'+@FIPS+'_M'+'
WHERE isdate(F6)= 1 and isnumeric(F6) = 1
) as x
group by x.FIPS, x.State, x.County, x.DataType, convert(varchar(7), x.[RecordingDate], 120)
order by x.FIPS
'
(@STRSQL)
EXECUTE
(@STRSQL)
FETCH
NEXTFROM MYCURINTO @FIPS
END
CLOSE
MYCUR
DEALLOCATE
MYCUR