title: SQL Server 2012 Using Declared Variables in a Join
body: <p>I'm quite new to SQL Server so hopefully this makes sense :)</p>
  
  <p>I'm trying to declare variables to be used in an INNER JOIN.</p>
  
  <p>If you take a look at my code, you'll see what I'm trying to do, without me needing to go into too much detail. Let me know if you need more info. Is that syntax possible?</p>
  
  <p>EDIT: See new attempt below</p>
  
  <pre><code>    --State - If suburb/postcode, could use postcode lookup
  Declare @Missing as nvarchar(255),
   @MissingUpdate as nvarchar(255),
   @MatchA as nvarchar(255),
   @MatchB as nvarchar(255),
   @Reason as nvarchar(255);
  
  Set @Missing = '[StateEXPORT]'; -- field to update
  Set @MissingUpdate = '[State]'; -- field in postcode lookup to pull in
  Set @MatchA = '[PostcodeEXPORT]'; -- field in master field to match with
  Set @MatchB = '[Pcode]'; -- field in postcode lookup to match with
  Set @Reason = 'Contactable - Needs verificiation - @MissingUpdate taken from Lookup'; -- reason here
  
  update [BT].[dbo].[test]
  set @Missing = b.@MissingUpdate,    
      FinalPot =  @Reason
  FROM [BT].[dbo].[test] a
  INNER JOIN [BT].[dbo].[Postcode Lookup] b
  ON a.@MatchA = b.@MatchB
  where (@Missing is null or @Missing = '0') and [AddressSource] != ('Uncontactable')
  GO
  </code></pre>
  
  <p>EDIT: SECOND ATTEMPT:</p>
  
  <pre><code>set @sql = 'update [BT].[dbo].[test] set ' + quotename(@Missing) + '= b.' +     quotename(@MissingUpdate) + ', FinalPot = ' + @Reason + 'FROM [BT].[dbo].[test] a INNER JOIN [BT].[dbo].[Postcode Lookup] b ON a.' + quotename(@MatchA) + ' = b.' + quotename(@MatchB) + 'where (' + quotename(@Missing) + 'is null or' + quotename(@Missing) + ' = 0 and [AddressSource] != "(Uncontactable)"'
  
  exec (@sql)
  </code></pre>
  
  <p>Thanks for your help,
  Lucas</p>