Hi. My name is Momba and I'm a T-SQL noob....So I've got the following hard-coded query:[code="sql"]select * TableCurrent WHERE BRANCHID='950' AND (DISC_DTE IS NULL OR DISC_DTE > 20070630)unionselect * from Table_2007_2008WHERE BRANCHID='950' AND (DISC_DTE IS NULL OR DISC_DTE > 20070630)unionselect * from Table_2008_2009WHERE BRANCHID='950' AND (DISC_DTE IS NULL OR DISC_DTE > 20070630)unionselect * from Table_2009_2010WHERE BRANCHID='950' AND (DISC_DTE IS NULL OR DISC_DTE > 20070630)unionselect * from Table_2010_2011WHERE BRANCHID='950' AND (DISC_DTE IS NULL OR DISC_DTE > 20070630)unionselect * from Table_2011_2012WHERE BRANCHID='950' AND (DISC_DTE IS NULL OR DISC_DTE > 20070630)[/code]At the end of each fiscal year (June 30th) a new archive is made of the current table and I end up having to dig through everything to get what I need. And this is my best attempt to making it dynamic:[code="sql"]Use TableCurrentDeclare @loopYrbeg intDeclare @loopYrend intDeclare @tablename sysnameDeclare @SQL varchar(MAX)Set @loopYrbeg = 2007begin While @loopYrbeg < year( getdate() ) begin Set @loopYrend = @loopYrbeg + 1 Set @tablename = 'Table_' + CONVERT(varchar(4), @loopYrbeg) + '_' + CONVERT(varchar(4), @loopYrend) Set @sql = 'select * from ' + @tablename +char(10)+ 'WHERE BRANCHID='950' AND (DISC_DTE IS NULL OR DISC_DTE > 20070630)'+char(10)+ 'union'+char(10) Set @loopYrbeg = @loopYrbeg + 1 endexec (@sql)select * TableCurrent WHERE BRANCHID='950' AND (DISC_DTE IS NULL OR DISC_DTE > 20070630)end[/code]...Unfortunately my best attempt doesn't work as it should. Please advise. Thank you.
↧