SQL - use variable as column in SELECT statement and WHERE clause <p>I'm trying to pull the students that are tardy for the previous period from our attendance database (SQL Server 2008). The period attendance is stored in <code>ATT.A1, ATT.A2 ... ATT.A7</code>. I want to schedule a job to run each hour, starting at 9am, and pull the tardy students, but I can't figure out the code. </p> <p>Here's my code (pseudo-code):</p> <pre><code>Declare @Period varchar(6) Set @Period = 'att.a' + Cast((DATENAME(hour, GETDATE()) - 8) as varchar(1)) Select SC, SN, DT, @Period as Period, ATT.A1 From ATT Where SC = '9' and @Period = 'T' and DT = DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0) </code></pre> <p>When I use this, I get no results. If I remove <code>@Period = 'T'</code> from the Where clause, I get the following:</p> <pre><code>9 5177 2012-08-24 00:00:00.000 att.a1 T 9 5211 2012-08-24 00:00:00.000 att.a1 9 5225 2012-08-24 00:00:00.000 att.a1 T 9 5229 2012-08-24 00:00:00.000 att.a1 T 9 5235 2012-08-24 00:00:00.000 att.a1 V 9 5242 2012-08-24 00:00:00.000 att.a1 T 9 5268 2012-08-24 00:00:00.000 att.a1 </code></pre> <p>I know that when I use <code>@Period</code> in the <code>SELECT</code> statement and <code>WHERE</code> clause it's using the literal string value of <code>@Period</code>, but I need it to use the value of <code>@Period</code> as <code>Table.Column</code>. </p> <p>So, at 9:00 it will select from <code>ATT.A1</code>, 10:00 from <code>ATT.A2</code> ... 15:00 from <code>ATT.A7</code> and each time compare whether ATT.A# = 'T'</p> <p>I hope that's clear.</p> <p>Thanks, Anthony</p>