1

假设我有两张桌子:

  • 学生:ID、姓名、年龄、班级等
  • 条件:ID,条件

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%'

结果将是(条件,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
4

2 回答 2

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('')
) , '&LT;' , '<') , '&GT;' , '>') 

SET @CONDITIONS = (SELECT SUBSTRING(@CONDITIONS , 11 , LEN(@CONDITIONS)))

EXEC(@CONDITIONS)

这是应用条件的更一般化的方式。如果您只想应用一个条件,则在我们获取所有条件的查询中添加 where 子句。您可以针对一个或多个条件运行此查询。目前我已经编写了适用所有条件的查询。

sqlfiddle

于 2013-07-07T18:16:33.087 回答
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
于 2013-07-07T19:29:07.940 回答