Wrox Home  
Search P2P Archive for: Go

  Return to Index  

sql_language thread: S.O.S to Date query Gurus


Message #1 by speedguru@m... on Fri, 27 Apr 2001 13:10:16
RK,

In SQL Server, you can use the Top keyword in the select statement to 
limit the number of records returned. To get the most recent, rder the 
select by the date column using the Descending modifier. This will give 
you the set you want, although not in the order you want. If this is 
important, you can select into a temp table, then reselect from that 
table, reordering as you go. Here's sample code:

-------------------------------------------------------------------------
-------


  -- Set up variables to hold the selection criteria. 
  -- These could also be passed in as parameters to a stored procedure.
  Declare
      @CurrentDate DateTime,
      @Country VarChar(2)
  Set @CurrentDate =3D GetDate()     -- set to a different date if you 
want
  Set @Country =3D 'IN'     -- country to return

  -- Select the records you want into a temp table using Top
  Select Top 2  *
  Into #TempCountry
  From CountryTerm
  Where DateDiff(dd, Date, @CurrentDate) > 0
      And Country =3D @Country
  Order By Date Desc

  -- Reorder the results by reselecting out of the temp table
  -- with a different order by clause.
  Select *
  From #TempCountry
  Order by Date

  -- Clean up the temp table. This would automatically be dropped
  -- when the session ends.
  Drop Table #TempCountry


-------------------------------------------------------------------------
-------


Jeff Wilson
President
The Boolean Group, Inc.
(xxx) xxx-xxxx
Glendale, CA


  Return to Index