【问题标题】:Set the diagonal values in SQL query with while loop in SQL Server在 SQL Server 中使用 while 循环设置 SQL 查询中的对角线值
【发布时间】:2021-04-02 20:19:39
【问题描述】:

我有一个这样的计数变量:

declare @count as int = 1

我想循环 3 行并在 select 语句中设置对角线值

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 个表 -> table1,但我想要类似的输出。

有人可以指导我吗?

【问题讨论】:

  • 请详细说明这件事的背景。对于您尝试解决的整体问题,SQL 似乎不是正确的工具。
  • 什么是对角线值?为什么要在循环中这样做,而不是在适当的记录上设置值?
  • SQL 表代表 无序 集。 “对角线”没有意义。
  • 在问另一个问题之前,我建议您阅读以下内容:Provide a Minimal Complete Verifiable Example (MCVE)Why should I provide a MCVE
  • 您想生成select 语句,为table1 中的每个 行输出一行(如果有),但只包含常量值?

标签: sql sql-server tsql stored-procedures


【解决方案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;

不会想到用例。

【讨论】:

  • 感谢分享,它给了我一个想法并实现了它。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-18
  • 2016-09-13
  • 1970-01-01
  • 2013-10-27
  • 2020-03-01
  • 2018-06-20
  • 2018-10-28
相关资源
最近更新 更多