代码之家  ›  专栏  ›  技术社区  ›  David Fox

当在WHERE子句中引用时,select动态字符串具有不同的值

  •  3
  • David Fox  · 技术社区  · 14 年前

    我动态地选择使用另一个字符串构建的字符串。所以,如果string1='david banner',那么 MyDynamicString 应为“dbanne”

    Select 
    ...
    , Left(
        left((select top 1 strval from dbo.SPLIT(string1,' ')) //first word
        ,1) //first character
        + (select top 1 strval from dbo.SPLIT(string1,' ') 
            //second word
            where strval not in (select top 1 strval from dbo.SPLIT(string1,' '))) 
    ,6) //1st character of 1st word, followed by up to 5 characters of second word
    [MyDynamicString]
    ,...
    From table1 Join table2 on table1pkey=table2fkey
    Where MyDynamicString <> table2.someotherfield
    

    我知道表2.其他领域 不平等 到动态字符串。但是,当我将WHERE子句中的mydynamicString替换为完整的左(左(等)。功能,按预期工作。

    稍后在查询中不能引用此字符串吗?我必须用左边(左边等)来建造它吗?在WHERE子句中每次都起作用?

    2 回复  |  直到 14 年前
        1
  •  3
  •   dcp    14 年前

    如果您按照上面的方法操作,那么答案是“是”,您必须在WHERE子句中重新创建它。

    作为替代方案,您可以使用内联视图:

        Select 
        ...
        , X.theString
        ,...
        From table1 Join table2 on table1pkey=table2fkey
           , (SELECT 
              string1
             ,Left(
                left((select top 1 strval from dbo.SPLIT(string1,' ')) //first word
                     ,1) //first character
                + (select top 1 strval from dbo.SPLIT(string1,' ') 
                //second word
                where strval not in (select top 1 strval from dbo.SPLIT(string1,' '))) 
               ,6) theString //1st character of 1st word, followed by up to 5 characters of second word
             FROM table1
           ) X
        Where X.theString <> table2.someotherfield
          AND X.string1 = <whatever you need to join it to>
    
        2
  •  1
  •   JohnFx    14 年前

    在SQL 2008中,可以在ORDER BY子句中使用别名,但不能在WHERE子句中使用别名。

    为什么不将计算打包到一个用户定义函数(UDF)中,以避免违反DRY,并使查询更具可读性?

    如果重要的话,这里有一个 article 这解释了为什么不能在HAVING、WHERE或GROUP BY中使用列别名。