I have a temp table like: #temp321
select * from #temp321
it’s return value like
Field1|Field2|Field3|....|FieldN|
--------------------------------
Value1|Value2|Value3|....|ValueN|
This #temp321 table is auto generated from another set of query.So, the number of #temp321 table’s column can be vary(1-25). But their will be always a single row. Now i need to write a where statement using those value.
Example :
where Field1='Value1' and Field2='Value2' and Field3='Value3'.....FieldN='ValueN'..(depends on number of column available into the #temp321 table)
How i do it. Thanks in advance
You can do this:
Update: This what I could do:
JOINthe two tables dynamically instead of theWHEREclause:How this works?
First I generated the
JOINcondition dynamically, by getting the list of the columns names from the temp table and the other list of columns’ names from the other table. Note that it. I used the columns’ORDINAL_POSITIONs, which is a metadata stored in the tableinformation_schema.columnsfor each column in the database, to compare the list of columns names from the two tables. For exapmle the column with the ordincary postition 1 will be joined with the column name with the ordinary position 1 from the second table, and so so. So, you have to watch out the temp table columns positions so that the columns listed in the same order of the other columns list of the second table.Update2:
Generate the
WHEREclause dynamically:If you want to generate the
WHEREclause dynamically instead of usingJOIN, in this case it will need more work. Like so:How this works?
Since the temp table contains only one rows with the values that will be used to form the dynamically created
WHEREclause, IUNPIVOTed this one rows into two columns:fieldname: field1, field2, ...andfieldvalue: value1, value2, ....Later I joined this unpivoted columns with the two tables I used with my first query:
and:
With the join condition be the same as the condition in the first case, by the ordinal positions of the columns in the two tables.
Generate the
WHEREclause dynamically, with dynamicallyUNPIVOTing the temp tables’ values:But the previous approach has a big problem. The selection of
You need to unpivot the table temp dynamically like so:
But, in order to use the dynamically unpivoted table later in our query, you have to create a temp table:
So that you could use it like so:
Here is the updated sql with dynamic unpivot: