Forum Discussion
Why Slno Chnages
I was trying to solve a sql puzzle
Using Microsoft SQL Server 2022 (RTM-CU15-GDR) (KB5046059) - 16.0.4150.1
drop table if exists [dbo].[MissingValue]
CREATE TABLE [dbo].[MissingValue]
(
[charValue] [varchar](1) NULL,
[ayValue] [int] NULL
)
GO
--Insert Data
truncate table [dbo].[MissingValue]
INSERT INTO [dbo].[MissingValue](charValue,ayValue)
VALUES
('A', 1),
('', 23),
('', 21),
('', 22),
('B', 34),
('', 31),
('', 89),
('C', 222),
('', 10)
--Verify Data
SELECT charValue,ayValue FROM [MissingValue]
;with rowcte as
(
select charvalue,ayvalue ,
row_number() over (order by (select 1)) as slno
from [missingvalue]
)
select a.charvalue,a.ayvalue,a.slno
--case when a.charvalue >'' then lead(a.slno) over( order by a.charvalue desc)
--else 0 end as nextval
from rowcte a
output
----------
;with rowcte as
(
select charvalue,ayvalue ,
row_number() over (order by (select 1)) as slno
from [missingvalue]
)
select a.charvalue,a.ayvalue,a.slno,
case when a.charvalue >'' then lead(a.slno) over( order by a.charvalue desc)
else 0 end as nextval
from rowcte a
output changes
Why Orginal Slno Vlaue changed just enabling nextval column
C= 1, B = 2, A = 3 .
Is this a bug ?
2 Replies
- rodgerkongIron Contributor
Check the xml of execute plan, it looks like function lead() cause row_number() in cte runs delay. If you assign cte result to a table variant, then getting next value from table variant will gain correct result.
drop table if exists [dbo].[MissingValue] CREATE TABLE [dbo].[MissingValue] ( [charValue] [varchar](1) NULL, [ayValue] [int] NULL, ) GO --Insert Data truncate table [dbo].[MissingValue] INSERT INTO [dbo].[MissingValue](charValue,ayValue) VALUES ('A', 1), ('', 23), ('', 21), ('', 22), ('B', 34), ('', 31), ('', 89), ('C', 222), ('', 10) declare @rowcte table([charValue] [varchar](1), [ayValue] [int], slno int) insert into @rowcte select charvalue,ayvalue , row_number() over (order by (select 1)) as slno from [missingvalue] select a.charvalue,a.ayvalue,a.slno, case when a.charvalue >'' then lead(a.slno) over( order by a.charvalue desc) else 0 end as nextval from @rowcte a- masriniCopper Contributor