动态AND子句

时间:2014-01-23 11:12:17

标签: sql sql-server

在存储过程中,我想只在满足特定条件时才在查询中包含AND子句。

INSERT INTO #firstResults   
 SELECT x, y, z  FROM ep  
 WHERE ep.proposedBy = @Id  
 AND ep.pId IN ( SELECT DISTINCT pId FROM #tempProj)

只有当#tempProj不为空时,'AND'子句才会加入 实现这一目标最优雅的方式是什么?

我在sql server 2008上 由于这将在proc上重复多次,我希望避免分支IF语句。

3 个答案:

答案 0 :(得分:2)

试试这个......

AND (ep.pId IN (SELECT DISTINCT pId FROM #tempProj) 
                OR (SELECT COUNT(*) FROM #tempProj) = 0))

答案 1 :(得分:1)

IF EXISTS (SELECT * FROM #tempProj)
 BEGIN
    INSERT INTO #firstResults   
    SELECT x, y, z  FROM ep  
    WHERE ep.proposedBy = @Id  
    AND ep.pId IN ( SELECT DISTINCT pId FROM #tempProj)
 END
ELSE
  BEGIN
    INSERT INTO #firstResults   
    SELECT x, y, z  FROM ep  
    WHERE ep.proposedBy = @Id 
  END

答案 2 :(得分:0)

IF EXISTS (SELECT TOP 1 NULL FROM #tempProj)
BEGIN
INSERT INTO #firstResults   
 SELECT x, y, z  FROM ep  
 WHERE ep.proposedBy = @Id  
 AND ep.pId IN ( SELECT DISTINCT pId FROM #tempProj)
END
ELSE
BEGIN
 INSERT INTO #firstResults   
 SELECT x, y, z  FROM ep  
 WHERE ep.proposedBy = @Id  
END