I have to check a few foreign keys in a loop and need to replace the name of the foreign key field with a variable (@fk_field for example).
My query looks like this:
SELECT
ad.id
, ad.@fk_field
, a1.@jnktn_field
FROM @tblname tbl LEFT JOIN @jnktn_tbl jnktn ON tbl.@fk_field=jnktn.@jnktn_field
WHERE ad.FK1 <> isnull(a1.ID,0)
Apparently it’s not possible to use a variable directly after a point like I did, but I need to do this to refer to the right table. So, how do I use variables to insert the fieldnames which were set before the SQL query?
Depending on where and how you use that query you could use
SQLCMD variables
EXECUTE Statement
Multiple JOIN clauses
UPDATE: This last example should require a bit of effort to get the query right and might not work at all depending on your exact requirements. The idea is to join to all referenced tables and set all fields from these tables to
NULLexcept for the table with the key specified in the variable.