---
title: "How can I use select in a SQL Server while loop?"  
description: "How can I use select in a SQL Server while loop?"  
author: "Anonymous User"  
published: 2013-10-22  
updated: 2013-10-22  
canonical: https://www.mindstick.com/forum/1701/how-can-i-use-select-in-a-sql-server-while-loop  
category: "mssql server"  
tags: ["mssql server"]  
reading_time: 1 minute  

---

# How can I use select in a SQL Server while loop?

How can I use [select](https://www.mindstick.com/forum/160534/orderby-then-select-vs-select-then-orderby-performance) in a SQL [Server while](https://answers.mindstick.com/qa/95219/why-does-my-microsoft-outlook-says-not-connected-to-the-server-while-i-can-get-the-same-email-on-my-iphone) loop? Below have my [demo](https://www.mindstick.com/forum/157370/how-to-swap-neighbor-characters-in-string-e-g-string-demo-would-be-edom) [code](https://yourviews.mindstick.com/view/85458/alan-turing-the-mastermind-behind-cracking-the-enigma-code-during-world-war-ii): -

```
 declare @loopVal integer
 set @loopVal =1
 while (@loopVal <10)
 begin
   select @loopVal as m;
   set @loopVal =@loopVal +1
 END 
```

\
I want it to return all select [results](https://yourviews.mindstick.com/story/4497/usage-of-baking-soda-magical-results) in [one table](https://www.mindstick.com/forum/538/copy-one-table-to-another-in-sql-server-automatically) but it will returns 10 separate table ... how can I achieve my task?

Please help me out…!!!!

\

## Replies

### Reply by Samuel Fernandes

```
declare @loopVal integer
DECLARE @testTable TABLE(
   /*Write your data type here*/
)
 set @loopVal =1
 while (@loopVal <10)
 begin
   insert into @testTable select @loopVal;
   set @loopVal =@loopVal +1
 END
select * from @testTable
```


---

Original Source: https://www.mindstick.com/forum/1701/how-can-i-use-select-in-a-sql-server-while-loop

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
