DECLARE @tablename VARCHAR (30), @tablename_1 VARCHAR (30),@tablename_2 VARCHAR (30),@fsc VARCHAR (10), @sql VARCHAR (5000) ,@fsc_1 VARCHAR (10),@fsc_2 VARCHAR (10) SET @fsc = (SELECT min(fscprdid) FROM fscprd WHERE cseflg = ‘n‘) SET @fsc_1 = (SELECT max(fscprdid) FROM fscprd WHERE cseflg = ‘y‘) SET @fsc_2 = (SELECT max(fscprdid) FROM fscprd WHERE cseflg = ‘y‘ AND fscprdid NOT IN (SELECT max(fscprdid) FROM fscprd WHERE cseflg = ‘y‘)) SET @tablename = ‘stockbth_‘+@fsc SET @tablename_1 = ‘stockbth_‘+@fsc_1 SET @tablename_2 = ‘stockbth_‘+@fsc_2 --SELECT @tablename ,@fsc --SELECT @tablename_1 --SELECT @tablename_2 SET @sql =‘insert into E9_Scm_Gdshnd_yyshop select * from openquery([E91],‘ SET @sql=@sql+ ‘ ‘‘ SELECT stockbth.gdsid , stockbth.fscprdid , stockbth.actdat , stockbth.prvid , stockbth.prvempid , stockbth.bllid , stockbth.blldes , CAST (stockbth.srcbllno AS CHAR (20)) AS srcbllno , CAST (stockbth.dbtcrt*-1 AS VARCHAR (2)) AS dbtcrt , stockbth.qty , stockbth.savdptid , stockbth.vlddat , stockbth.bthno , stockbth.dptid , stockbth.prc , stockbth.amt from ‘+ @tablename + ‘ as stockbth where stockbth.savdptid IN (‘‘‘‘602‘‘‘‘,‘‘‘‘603‘‘‘‘) AND actdat >=CONVERT (VARCHAR (8), DATEADD (dd, -12, GETDATE ()), 112) AND stockbth.fscprdid = ‘‘‘‘‘+@fsc+‘‘‘‘‘ ‘‘) ‘ exec(@sql)