有没有更好的方法来进行此查询?

时间:2014-04-10 19:21:14

标签: sql sql-server performance tsql

我想知道是否有更好的方法来编写以下查询:

IF EXISTS (SELECT * 
           FROM   master_list 
           WHERE  code = 'r_params') 
  BEGIN 
      UPDATE master_list 
      SET    code = 'w_params' 
      WHERE  code = 'r_params' 
             AND NOT name_1 = 'pH' 
             AND NOT name_2 = 'Flow' 
             AND NOT name_3 = 'Temperature' 

      SELECT * 
      FROM   r_master_list 
      WHERE  code = 'r_params' 

      SELECT * 
      FROM   r_master_list 
      WHERE  code = 'w_params' 
  END

由于

4 个答案:

答案 0 :(得分:0)

SELECT 1可能会更快

IF EXISTS (SELECT 1 
           FROM   master_list 
           WHERE  code = 'r_params') 
  BEGIN 
      UPDATE master_list 
      SET    code = 'w_params' 
      WHERE  code = 'r_params' 
             AND name_1 <> 'pH' 
             AND name_2 <> 'Flow' 
             AND name_3 <> 'Temperature' 

      SELECT * 
      FROM   r_master_list 
      WHERE  code = 'r_params' 

      SELECT * 
      FROM   r_master_list 
      WHERE  code = 'w_params' 
  END

答案 1 :(得分:0)

if exists (select * from MASTER_LIST where Code = 'r_params')
begin
    update MASTER_LIST 
      set Code = 'w_params' 
      where Code = 'r_params' 
      AND  Name_1 <> 'pH' 
      AND  Name_2 <> 'Flow' 
      AND  Name_3 <> 'Temperature'

 select * from R_MASTER_LIST  WHERE Code = 'r_params'

 select * from R_MASTER_LIST WHERE Code = 'w_params'
end

答案 2 :(得分:0)

不考虑客户希望接收数据的形式,更好的方法是将两个结果集合并为一个

IF EXISTS (SELECT * 
    FROM   master_list 
    WHERE  code = 'r_params') 
BEGIN 
    UPDATE master_list 
    SET    code = 'w_params' 
    WHERE  code = 'r_params' 
        AND name_1 <> 'pH' 
        AND name_2 <> 'Flow' 
        AND name_3 <> 'Temperature' 

    SELECT * 
    FROM   r_master_list 
    WHERE  code IN ('r_params', 'w_params')
END

这样您就可以r_master_list而不是两个查询。客户端将收到完全相同的数据;如果他需要,只有他有责任将其分成不同的结果集。性能和效率方面,应该是首选解决方案。

<强>更新

正如德鲁所暗示的,你可能也想制作你的“EXISTS&#39;像这样的函数子查询:

IF EXISTS (SELECT 1 
FROM   master_list 
    WHERE  code = 'r_params') 

关于这个问题更有效率或者没有效率存在争议。德鲁似乎相信它是;我无法告诉你。但! Drew没有提到这种方法仍有优势:如果您想在整个代码库中使用SELECT查找*个查询,您会发现它很方便您的所有EXISTS个功能子查询都使用SELECT 1模式,这样您就不会不必要地接触到这些模式。它可能不多,但我认为值得一提。

答案 3 :(得分:0)

这是多余的 更新的一个条件是WHERE code ='r_params'

IF EXISTS (SELECT * 
           FROM   master_list 
           WHERE  code = 'r_params') 

这就足够了

  UPDATE master_list 
  SET    code = 'w_params' 
  WHERE  code = 'r_params' 
         AND NOT name_1 = 'pH' 
         AND NOT name_2 = 'Flow' 
         AND NOT name_3 = 'Temperature' 

  SELECT * 
  FROM   r_master_list 
  WHERE  code = 'r_params' 

  SELECT * 
  FROM   r_master_list 
  WHERE  code = 'w_params' 

唯一的区别是,即使没有'r_params',你也会获得最后的选择

最后两个可以合并

SELECT * 
  FROM r_master_list 
 WHERE code in  ('r_params','w_params') 
 order by code