Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Select TOP 1 in SQL Server 2008
Message
General information
Forum:
Microsoft SQL Server
Category:
SQL syntax
Environment versions
SQL Server:
SQL Server 2005
Miscellaneous
Thread ID:
01364660
Message ID:
01364676
Views:
14
This message has been marked as the solution to the initial question of the thread.
>Hi everybody,
>
>Would you please explain why SELECT TOP 1 @ID = ID from myTable where ID > NotExistingID will return the first ID ? I would expect it to return null in this case.
>
>
>declare @Test table (id int identity, TestFld nvarchar(max))
>insert into @Test values ('Test Test Test one more Test')
>insert into @Test values ('one two three four five')
>insert into @Test values ('once twice once twice once twice')
>declare @AllWords nvarchar(max), @ID int, @CurrentID int 
>select top 1 @ID = ID, @AllWords = TestFld from @Test
>print @ID
>select * from @Test 
>--while @ID is not NULL
>--   begin
>--   set @CurrentID = @ID
>--select Item, ID from @Test T, dbo.ufn_Alines(T.TestFld,' ')  having COUNT(Item) >=3 
>--   select Item from dbo.ufn_Alines(@AllWords,' ') group by Item having COUNT(Item)>=3
>--   select top 1 @ID = ID, @AllWords = TestFld from @Test where ID > @CurrentID
>--   END
>
> select top 1 @ID = ID, @AllWords = TestFld from @Test where ID > 3
> print @ID
>
>UPDATE. Re-setting @ID to NULL before this statement helps, otherwise @ID remains the previous @ID. Interesting.

This is the same for all versions of SQL Server.
When you use SELECT to assign variable value and no records are returned, the value of the variable remains the same. If you want to be NULL you must use SET command:
SET @Id = (SELECT TOP 1 Id FROM .....)
Against Stupidity the Gods themselves Contend in Vain - Johann Christoph Friedrich von Schiller
The only thing normal about database guys is their tables.
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform