2010-09-01 66 views
0

我将问题简化为以下select语句。在选择语句创建的列上无效的列名称

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语句中获取值的列。

有没有办法做到上述没有得到 无效的列名称aVariable错误?

+0

的例子并没有多大意义,即使它是正确的语法,这是实际上是相同的话说,“其中1 = 1”。你能举一个更具体的例子吗? – TML 2010-09-01 10:21:59

+0

您需要更新声明 - 请参阅我的答案。 – Hogan 2010-09-01 10:30:35

+0

我不明白你选择的答案作为正确的作品 - 看到我编辑的答案。 – Hogan 2010-09-01 23:18:01

回答

3
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 
+0

抱歉误会,我更新了这个问题。 – Stavros 2010-09-01 10:26:21

+0

更新了答案。 – 2010-09-01 10:28:41

+0

关键字'where'附近的语法错误。 – Stavros 2010-09-01 10:32:40

1

SELECT必须像这样:

select 
    u.UserId, 
    1 as aVariable 
from TblUser u 
+0

抱歉误会,我更新了这个问题。 – Stavros 2010-09-01 10:25:26

+0

你的问题仍然不清楚。你想实现什么? – 2010-09-01 12:21:39

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 

上面的声明表示如果有一个用户被禁用,则选择来自tbluser的所有用户。

我想你想看到表中的用户被禁用。如果是这样,那么你想要以下选择语句:

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

给这个镜头。

先前回答删除,因为问题有点不清楚。

+0

抱歉误会,我更新了这个问题。 – Stavros 2010-09-01 10:26:52

+0

aVariable不是一个参数,它是一个列名,我想在where子句中使用它。 – Stavros 2010-09-01 10:27:33

+0

您无法更改select语句中的列值 - 只能读取值...如果您希望新的输出列使用'as'如果要更改表使用更新。 – Hogan 2010-09-01 10:36:15

1

你需要这样做:

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 
+0

我在寻找更好的东西,因为case语句块中的select语句更加复杂和缓慢:( – Stavros 2010-09-01 10:33:57

+0

也许你可以将case语句包装到一个函数中 - 这可能会加快速度,它肯定会使它更具可读性。你能够真正发布真正的问题吗?有人可能能够一起提供不同的解决方案。 – codingbadger 2010-09-01 10:38:35

+0

不使用函数!!!使用连接。 – Hogan 2010-09-01 11:01:33