Select all records between two numbers using loop in SQL Server

Shud
 
on Apr 11, 2021 11:09 PM
614 Views

i have a table: tbl_test

this table has 2 columns name: age, weight

this table has 2 row inserted:

age weight

3 5

4 6

now i want to print this:

age weight

0 null

1 null

2 null

3 5

4 6

5 null

6 null

7 null

..

..

..

60 null

and so on....

how can we do this, please suggest.

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Apr 12, 2021 03:32 AM

Hi Shud,

Refer below query.

SQL

CREATE TABLE #tbl_test
(
    age INT,
    weight INT
)

INSERT INTO #tbl_test VALUES (3,5)
INSERT INTO #tbl_test VALUES (4,6)

CREATE TABLE #tbl_test_out
(
    age INT,
    weight INT
)

DECLARE @Counter INT
SET @Counter = 0

WHILE (@Counter <= 60)
BEGIN
	DECLARE @Weight INT
	SET @Weight = (SELECT Weight FROM #tbl_test WHERE age = @Counter)

	INSERT INTO #tbl_test_out VALUES (@Counter, @Weight)

	SET @Counter = @Counter + 1
	CONTINUE;
END


SELECT * FROM #tbl_test_out

DROP TABLE #tbl_test_out
DROP TABLE #tbl_test