SQL Server 2005 Setting a variable to the result of a select query

前端 未结 6 1006
面向向阳花
面向向阳花 2021-02-05 00:31

How do I set a variable to the result of select query without using a stored procedure?


I want to do something like: OOdate DATETIME

SET OOdate =          


        
6条回答
  •  情深已故
    2021-02-05 00:45

    You could also just put the first SELECT in a subquery. Since most optimizers will fold it into a constant anyway, there should not be a performance hit on this.

    Incidentally, since you are using a predicate like this:

    CONVERT(...) = CONVERT(...)
    

    that predicate expression cannot be optimized properly or use indexes on the columns reference by the CONVERT() function.

    Here is one way to make the original query somewhat better:

    DECLARE @ooDate datetime
    SELECT @ooDate = OO.Date FROM OLAP.OutageHours AS OO where OO.OutageID = 1
    
    SELECT 
      COUNT(FF.HALID)
    FROM
      Outages.FaultsInOutages AS OFIO 
      INNER JOIN Faults.Faults as FF ON 
        FF.HALID = OFIO.HALID 
    WHERE
      FF.FaultDate >= @ooDate AND
      FF.FaultDate < DATEADD(day, 1, @ooDate) AND
      OFIO.OutageID = 1
    

    This version could leverage in index that involved FaultDate, and achieves the same goal.

    Here it is, rewritten to use a subquery to avoid the variable declaration and subsequent SELECT.

    SELECT 
      COUNT(FF.HALID)
    FROM
      Outages.FaultsInOutages AS OFIO 
      INNER JOIN Faults.Faults as FF ON 
        FF.HALID = OFIO.HALID 
    WHERE
      CONVERT(varchar(10), FF.FaultDate, 126) = (SELECT CONVERT(varchar(10), OO.Date, 126) FROM OLAP.OutageHours AS OO where OO.OutageID = 1) AND
      OFIO.OutageID = 1
    

    Note that this approach has the same index usage issue as the original, because of the use of CONVERT() on FF.FaultDate. This could be remedied by adding the subquery twice, but you would be better served with the variable approach in this case. This last version is only for demonstration.

    Regards.

提交回复
热议问题