2012-09-07 41 views
0

我想要做以下查詢:創建從查詢結果中的SQL變量在同一個查詢中使用

SELECT SUBSTRING(violations, CHARINDEX('X', violations, 0), 5) AS 'violations', definition, value, date 
FROM NewViolations WHERE CHARINDEX('X', violations, 0) > 0 

不過,我似乎無法弄清楚如何把CHARINDEX('X', violations, 0)成變量(VarX),使我最終是這樣的:

SELECT SUBSTRING(violations, VarX, 5) AS 'violations', definition, value, date 
FROM NewViolations WHERE VarX > 0 

我這樣做是爲了避免運行CHARINDEX兩次。

回答

2

嘗試:

select substring(violations, location, 5) as 'violations', definition, value, date 
from (select violations, charindex('x',violations,0) location, definition, value, date 
     from NewViolations) a 
where a.location>0 

爲了說明的緣故,有點少打字,人們可以(雖然大部分可能會皺眉吧):

select substring(violations, location, 5) as 'violations', definition, value, date 
from (select *, charindex('x',violations,0) location 
     from NewViolations) a 
where a.location>0 
+0

對不起,我的例子是不完整的。除了子字符串之外,我還需要一堆來自同一個表的列。 – Andrew

+0

認爲你應該能夠將它們添加到子選擇中,然後將它們拉出到主選擇中。 –

+0

爲什麼你的第二個例子會皺起眉頭? – Andrew

1

假設的SQL Server 2005 +,你可以使用CTE:

WITH cteCharIndex AS (
    SELECT violations, CHARINDEX('X', violations, 0) AS PosOfX 
     FROM NewViolations 
) 
SELECT SUBSTRING(violations, PosOfX, 5) AS 'violations' 
    FROM cteCharIndex 
    WHERE PosOfX > 0; 
相關問題