简体   繁体   中英

Dynamic where clause by reading values inside a table

Can you help me to get the student 'Lindsay' class name and session description values reading Rules table
Table name, columnName and value columns?

在此处输入图片说明

Try this:

SELECT a.FirstName, b.ClassName, c.Description FROM Student a
LEFT OUTER JOIN Rule r1 ON a.RuleID = r1.RuleID AND r1.[Table Name] = 'Class' AND r1.[Column Name] = 'ClassID'
LEFT OUTER JOIN Rule r2 ON a.RuleID = r2.RuleID AND r2.[Table Name] = 'Session' AND r2.[Column Name] = 'SessionID'
LEFT OUTER JOIN Class b ON b.ClassID = r1.Value
LEFT OUTER JOIN Session c ON c.SessionID = r2.Value

If it needs to be dynamically reading the rule table, then you could use dynamic sql and cursor through the 'Rule' table first and just have the 'r1' join with 'r1.[Table Name]' and 'r1.[Column Name]' being dynamically populated from the cursor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM