在SQL Server中使用while循环设置SQL查询中的对角线值



我有一个计数变量,如下所示:

declare @count as int = 1

我想循环它3行,并在选择语句中设置对角线值

while (@count <= 3)
begin
-- Set the diagonal value in select statement
end

预期输出为

Select 1, Null, Null from table1 
Select Null,2,Null from table1
Select Null,Null,3 from table1

为了简单起见,我选择了1张桌子->表1,但我想要类似的输出。

有人能给我指路吗?

以下代码输出请求的语句:

declare @Count as Int = 1;
while @Count <= 3
begin
print Concat( 'select ', case @Count when 1 then '1' else 'NULL' end, ', ',
case @Count when 2 then '2' else 'NULL' end, ', ', case @Count when 3 then '3' else 'NULL' end,
' from table1;' );
set @Count += 1;
end;

用例不会跃然纸上。

最新更新