从查询结果中创建一个sql变量以在同一查询中使用

时间:2012-09-07 14:56:38

标签: 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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;