【问题标题】:Invalid column name, on select-statement created columns无效的列名,在选择语句创建的列上
【发布时间】:2010-09-01 10:18:35
【问题描述】:

我已将我的问题简化为以下选择语句。

select 
   u.UserId,
   aVariable = cast((case when exists(select * from TblUser u where u.Disabled=1) then 1 else 0 end) as bit), 
from TblUser u
where aVariable = 1

aVariable 不是表的列,而只是在此 select 语句中获取值的列。

有没有办法在没有得到 Invalid column name aVariable 错误?

【问题讨论】:

  • 这个例子没有多大意义,即使它是正确的语法,它实际上与说“where 1=1”是一样的。你能举一个更具体的例子吗?
  • 你需要更新声明——看我的回答。
  • 我不明白您选择正确的答案是如何工作的 - 请参阅我编辑的答案。
  • @Hogan:忘记 sql 语句中的逻辑。我需要的是语法。它是关于如何在我的“where”子句中使用 select-statement-column。

标签: sql sql-server-2005


【解决方案1】:
select q.* from (
select 
   u.UserId,
   cast((case when exists(select * from TblUser u where u.Disabled=1) then 1 else 0 end) as bit) as aVar, 
from TblUser u
)q 
where q.aVar = 1

【讨论】:

  • 我已经编辑了这个,所以它现在应该可以工作了。 SQL 缺少表别名。
【解决方案2】:

SELECT 必须如下所示:

select 
   u.UserId,
   1 as aVariable
from TblUser u

【讨论】:

    【解决方案3】:

    你需要这样做:

    select 
       u.UserId,
       aVariable = cast((case when exists(select * from TblUser u where u.Disabled=1) then 1 else 0 end) as bit), 
    from TblUser u
    where cast((case when exists(select * from TblUser u where u.Disabled=1) then 1 else 0 end) as bit) = 1
    

    【讨论】:

    • 我一直在寻找更好的东西,因为 case 块中的 select 语句更复杂,更慢:(
    • 也许您可以将 case 语句包装到一个函数中——这可能会加快速度。它肯定会使它更具可读性。您是否能够实际发布真正的问题。也许有人可以一起提供不同的解决方案。
    【解决方案4】:

    您选择正确的陈述毫无意义。

    select q.* from (
    select 
       u.UserId,
       cast((case when exists(select * from TblUser u where u.Disabled=1) then 1 else 0 end) as bit) as aVar, 
    from TblUser u
    )q 
    where q.aVar = 1
    

    上面的语句说如果有一个用户被禁用,则从 tbluser 中选择所有用户。

    我认为您希望查看表中被禁用的用户。如果是这样,那么您需要以下选择语句:

    SELECT userid, disabled as aVar
    FROM TblUser
    WHERE disabled = 1
    

    试一试。

    之前的回答被删除了,因为这个问题有点不清楚。

    【讨论】:

    • aVariable 不是参数,它是列名,我想在 where 子句中使用它。
    • 您不能在选择语句中更改列值——您只能读取值...如果您想要一个新的输出列,请使用as 如果您想更改表使用更新。
    • 列名“aVariable”无效。 :(
    • 您的表是否有一个名为 avariable 的列?如果没有,则无法更改。
    • 使用@符号作为前缀不仅用于参数,也用于局部变量。如果你想要一个局部变量,你需要在它前面加上一个 @ 并有一个声明语句。
    猜你喜欢
    • 2020-08-07
    • 2013-05-29
    • 1970-01-01
    • 1970-01-01
    • 2014-09-05
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多