Monday, March 12, 2012

Retrieving data in a Multiple Record Scenario

I have table "student" and it has 3 fields "Id", "Name" and "JoinDt".

Its contents are given below

Id Name JoinDt

1 One 1/1/2005

2 Two 2/2/2006

3 Three 3/3/2007

When I tried to execute the following query

declare @.Id int
declare @.Name varchar(50)

Select @.Id =Id, @.Name=Name From student

Where JoinDt>'1/1/2006' Order By JoinDt

Select @.Id ,@.Name

Iam getting the result like

3 Three

That means the query returns the value of last record in that cursor.

My doubt is whether this sort of queries will provide consistent results or not.

Yes the above query always give the last record.

First it will assign the 1 row value, then 2 row value ..... finally it will assign the last row value (somthing like loop).

|||

The simple & faster version of query ...

Select Top 1 @.Id =Id, @.Name=Name From student

Where JoinDt>'1/1/2006' Order By JoinDt Desc

Select @.Id ,@.Name

|||

If you are using @.ID and @.Name for display the out put then TSQL Look like,

Select Top 1 Id, Name From student

Where JoinDt>'1/1/2006' Order By JoinDt Desc

Regards

manoj

|||Thank U It worked!!!

No comments:

Post a Comment