0

Hello my code is as follows:

DECLARE @cnt INT = 0;
WHILE @cnt < 256
BEGIN
SELECT
ITEM1 ,
ITEM2 ,
ITEM3
FROM Table_Name
SET @cnt = @cnt + 3
End

I want to do like below:

DECLARE @cnt INT = 0;
WHILE @cnt < 256
BEGIN
SELECT
ITEM@cnt+1 ,
ITEM@cnt+2 ,
ITEM@cnt+3
FROM Table_Name
SET @cnt = @cnt + 3
End

So that it will be executed in a single loop. Please help me regarding this.

Thank you in advance

2
  • 1
    what are you trying to accomplish here? Why loop this? Commented Jun 25, 2018 at 16:21
  • 1
    what's the expected results supposed to look like Commented Jun 25, 2018 at 16:34

1 Answer 1

1

If you want to compose your query using variables, you must use dynamic TSQL to construct your select, then you can execute it with EXEC(...):

DECLARE @sql varchar(max)= ' SELECT '
DECLARE @cnt INT = 0;

WHILE @cnt < 256
    BEGIN
        set @cnt = @cnt + 1
        set @sql = @sql + ' ITEM' + cast(@cnt as varchar(max)) + ',' 
    End
set @sql = replace (@sql + ' from #table_name',', from',' from')

exec (@sql)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.