0

我想做以下查询:

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。

4

2 回答 2

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
于 2012-09-07T15:00:48.683 回答
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;
于 2012-09-07T15:02:26.220 回答