2010-06-17 27 views
3

我動態選擇使用另一個字符串構建的字符串。因此,如果字符串2 =「大衛旗幟」,然後MyDynamicString應該是「DBanne」在Where子句中引用時,選擇動態字符串具有不同的值

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 

我知道table2.someotherfield 不等於的動態字符串。然而,當我用Where的子句中的MyDynamicString替換爲完全左側(左側(等..函數,它按預期的方式工作)。

我可以在查詢中稍後引用此字符串嗎?是否必須使用左(左(等等。如果你這樣做,你有它上面的函數在where子句?

回答

3

各一次,那麼答案是肯定的,你必須在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> 
+1

+1光滑,現在測試 – 2010-06-17 14:46:39

+0

這是未經測試的,所以你可能不得不稍微調整語法,但我認爲這個想法應該可行。另請參閱我的最新編輯。確保在內聯視圖中添加列別名(即「theString」部分)。 – dcp 2010-06-17 14:48:10

+0

如何在此內聯視圖中引用table1.string1?內聯視圖的FROM子句對我​​來說還不清楚。我可以使用'FROM table1 JOIN table2 ON table1pkey = table2fkey',但是我必須重複Where子句嗎?在我的實際代碼中,Where子句有另外5或6個條件 – 2010-06-17 15:06:30

1

在SQL 2中008,您可以在ORDER BY CLAUSE中使用別名,但不能在where子句中使用。

爲什麼不將計算包裝到用戶定義的函數(UDF)中以避免違反DRY並且使查詢更具可讀性?

如果很重要,這裏是一個article,它解釋了爲什麼您不能在HAVING,WHERE或GROUP BY中使用列別名。

+0

@JohnFx - 如果這是他使用這種計算的唯一查詢,我認爲UDF是矯枉過正的,最好將查詢分解爲內聯視圖。就我個人而言,我寧願在查詢中看到它,所以我不必追蹤UDF來弄清楚發生了什麼。但是如果它的代碼將被許多查詢使用,我同意你100%UDF是要走的路。 – dcp 2010-06-17 15:00:01

+0

我喜歡這個 - 我想我必須在dcp的答案中的內聯視圖的FROM子句中重複自己。 – 2010-06-17 15:00:04

+0

@大衛 - 你不應該重複計算,它應該只在內聯視圖。或者,也許我誤解了? – dcp 2010-06-17 15:01:30

相關問題