Using Microsoft SQL Server 2008, let's say there is a table1 that keeps the selected ids of provinces, districts, communes and villages. And then there is table2 with the ids and names of provinces, districts, communes and villages. Provinces and districts are required fields and will always be filled. Communes and villages might be filled but might even not be filled as they are not required.
What is the best way to build a dynamical SQL statement without knowing if the ids for communes and villages are filled in table1 or not.
SELECT tbl1.province, tbl1.district, tbl1.commune, tbl1.village
FROM dbo.table1 AS tbl1
AND dbo.table2 AS tbl2
WHERE tbl1.province = tbl2.province_id
AND tbl1.district = tbl2.district_id
AND tbl1.commune = tbl2.commune_id
AND tbl1.village = tbl2.village_id
This statement gives wrong results if the id in table1 is not filled.