Why is my T-SQL (WHILE) not working?

In my code, I need to check if the specified column is zero and as close as possible to 0 (it can contain numbers from 0 to 50), so I tried the code below. It should start at 0 and test the request for each value. When @Results gets null, it should return. However, this does not work. Still prints 0.

declare @hold int
declare @Result int
set @hold0
set @Result=0

WHILE (@Result!=null)
BEGIN
select @Result=(SELECT Hold from Numbers WHERE Name='Test' AND Hold=@hold)
set @hold=@hold+1
END

print @hold
+3
source share
4 answers

First, you cannot check for NULL. NULL means an unknown value, so you do not know if it matches (or does not match) a specific value. @Result!=NULLUse instead@result IS NOT NULL

-, SQL, . SQL , . SQL, , , :

SELECT
    MIN(hold) + 1
FROM
    Numbers N1
WHERE
    N1.name = 'Test' AND
    NOT EXISTS
    (
        SELECT
            *
        FROM
            Numbers N2
        WHERE
            N2.name = 'Test' AND
            N2.hold = N1.hold + 1
    )

SQL Server: " 1 (MIN (hold) + 1) Numbers, (name = 'Test'), " " , (" ")". :

Name      Hold
--------  ----
Test      1
Test      2
NotTest   3
Test      20

SQL Server "Test" (1, 2, 20), , = Test hold = hold + 1. 1 2, . 2 , 3 . 20 , 21, :

Name      Hold
--------  ----
Test      2
Test      20

SQL Server MIN (hold) 2, 1, 3.

SQL Server , . SQL SQL Server, , . SQL Server , , .

( JOIN), ( WHERE ON , (MIN, MAX, AVG ..).

+4

WHILE (@Result is not null)
BEGIN
select @Result=(SELECT Hold from Numbers WHERE Name='Test' AND Hold=@hold)
set @hold=@hold+1
END
+1

:

declare @hold int
declare @Result int
set @hold=0
set @Result=0
declare @max int
SELECT @max=MAX(Hold) FROM Numbers

WHILE (@hold <= @max)
BEGIN
   select @Result=(SELECT Hold from Numbers WHERE Name='Test' AND Hold=@hold)

   set @hold=@hold+1
END

print @hold

T-SQL - (foreach) (temp) - :

-- Foreach with T-SQL while
DECLARE @tempTable TABLE (rownum int IDENTITY (1, 1) Primary key NOT NULL, Number int)
declare @RowCnt int
declare @MaxRows int
select @RowCnt = 1
select @MaxRows=count(*) from @tempTable
declare @number int

while @RowCnt <= @MaxRows
begin
    -- Number from given RowNumber
    SELECT @number=Number FROM @tempTable where rownum = @RowCnt

    -- next row
    Select @RowCnt = @RowCnt + 1
end
0

​​ Tom H.:

SELECT MIN(N1.hold) + 1
FROM Numbers N1
LEFT OUTER JOIN Numbers N2
    ON N2.Name = N1.Name AND N2.hold = N1.hold + 1
WHERE N1.name = 'Test' AND N2.name IS NULL

, SQL, . , SQL, N1 N2. .

0

Source: https://habr.com/ru/post/1756604/


All Articles