子查询引用新创建的列

时间:2018-02-13 19:59:57

标签: sql-server

我一直在尝试根据SQL Server docs编写子查询。我正在尝试将SQL Server查询写入

  1. 将varchar转换为int
  2. 选择varchar为null的行。
  3. 我的逻辑是:

    1. outer select + where子句获取新列(q5int)为NULL的所有行
    2. 创建执行强制转换的内部选择并创建新列(q5int)
    3. 我做错了什么?我很感激我的逻辑错误解释,而不仅仅是如何修复我的代码。

      select *  
      from 
          (select 
               *, cast (NULLIF(q5,'NULL') as int) as q5int 
           from 
               ft_merge)
      where
          q5int = NULL
      

2 个答案:

答案 0 :(得分:1)

您可以执行此操作无子查询

select *  
 from ft_merge
 WHERE try_convert(int,q5) is null

答案 1 :(得分:0)

让我们先分析您的查询

               select *  from (
                select *,cast (NULLIF(q5,'NULL') as int) as q5int 
                from ft_merge
                ) WHERE q5int=NULL

1.NULLIF(q5,'NULL')应该是NULLIF(q5,NULL)而不是引号

2.WHERE q5int = NULL应替换为“q5int IS NULL”

创建测试数据

       Select * into #ft_merge
        from
        (

              Select 1 AS ID,'111' AS q5
              union
              Select 2, null
                  union
              Select 3,'2222'
                  union
              Select 4,null 
        )t



       /* using your query */  
       select *  from (
      select *,cast(q5 as int) as q5int 
        from #ft_merge where ISNUMERIC(q5) > 0 or q5 is null
      )t WHERE q5int is NULL
      /* another optimal way of doing this */

      select *,cast(q5 as int) as q5int 
      from #ft_merge where NULLIF(q5,NULL) is null