【问题标题】:populate multiple variables based on row根据行填充多个变量
【发布时间】:2013-12-06 08:40:13
【问题描述】:

我有以下变量

  Declare @test1 int,
            @test2 int,
            @test3 int

有没有办法根据表中的行填充上述变量?目前我正在这样做。

select @test1 = value from tables where somecode = 'test1'
select @test2 = value from tables where somecode = 'test2'
select @test3 = value from tables where somecode = 'test3'

有没有更好的方法来做到这一点?即在一个单一的选择语句中?

这样的事情有可能吗?

SELECT @test1 = CASE code WHEN 'test1' THEN value END,
       @test2 = CASE code WHEN 'test2' THEN value END
  FROM myTable

【问题讨论】:

  • 尝试this分配给多个变量。

标签: sql sql-server tsql


【解决方案1】:
    select
    @test1 = max(case when <testcolumn> = 'test1' then col1 else null end),
    @test2 = max(case when <testcolumn> = 'test2 ' then col2 else null end),
    ...
    from
    <your table>
    where
   test column in ('test1','test2')

根据您的数据,您可能需要选择不同的或某种聚合以使其完全正确。

SQL Fiddle

【讨论】:

  • 这行不通我没有从单行中选择的多个列。
  • 这没有意义。如果您只有一行,除非您的表格只有一列,否则您就有多列。我错过了什么?
  • @Raju 你只有一列只有一行?所以你想为所有三个变量分配相同的值?
  • 对我根据不同代码带回行的混乱表示歉意,请参阅我已更新的答案
  • Nope 不起作用让第一个 null 第二个变量被赋值
猜你喜欢
  • 1970-01-01
  • 2012-12-17
  • 1970-01-01
  • 2018-02-18
  • 2017-03-07
  • 2021-05-28
  • 1970-01-01
  • 1970-01-01
  • 2019-05-22
相关资源
最近更新 更多