假设我有两张桌子:
Column Conditions.Condition包含一个SQL条件,例如“std.Age> 2”或“std.Class = 3”
我想做的事情如下:
SELECT std.Id as StudentId, con.Id as ConId
FROM Students as std,
Condition as con
WHERE con.Condition
也许是一个需要学生ID的函数?
我如何实现这一目标?
生:
1 , Yossi, 25, 3..
2 , David, 22, 3..
3 , Jhon, 5, 2..
4 , Smith, 25, 4..
条件:
1 , Age > 3
2 , Class = 4
3 , Name LIKE '%i%'
结果将是(Condition,Studnet):
(1,1) (1,2) (1,3) (1,4) // all are older than 3
(2,4) // only Smith is in class 4
(3,1) (3,2) (3,4) // all except jhon have an i in their name
答案 0 :(得分:2)
尝试以下查询:
DECLARE @CONDITIONS varchar(max) =
REPLACE(REPLACE((
SELECT'UNION ALL SELECT ID AS STUDENTID , ' + CONVERT(VARCHAR , ID ) + ' AS CONDITIONID FROM STUDENTS WHERE ' + CONDITION + ' '
FROM CONDITION
FOR XML PATH('')
) , '<' , '<') , '>' , '>')
SET @CONDITIONS = (SELECT SUBSTRING(@CONDITIONS , 11 , LEN(@CONDITIONS)))
EXEC(@CONDITIONS)
这是应用条件的更一般化的方法。如果你只想应用一个条件,那么在查询中添加where子句,从中获取所有条件。您可以针对一个或多个条件运行此查询。目前我已经编写了这个适用所有条件的查询。
答案 1 :(得分:0)
您必须构建一个包含条件的字符串,然后执行它。这就是所谓的“动态SQL”
举个例子:
DECLARE @sql Varchar(400)
SELECT @sql = 'SELECT * FROM MyTable WHERE ' + condition
FROM Conditions
WHERE cond_key = 1
-- This will yield you a full SQL statement, if the condition record
-- is there.
EXECUTE(@sql) -- And this will execute it