Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Select TOP 1 in SQL Server 2008
Message
Information générale
Forum:
Microsoft SQL Server
Catégorie:
Syntaxe SQL
Versions des environnements
SQL Server:
SQL Server 2005
Divers
Thread ID:
01364660
Message ID:
01364682
Vues:
14
Thanks, Boris. Do you think my code for looping through the records is OK?

>>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 .....)
>
If it's not broken, fix it until it is.


My Blog
Précédent
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform