Andrew
Andrew

Reputation: 2549

Create an sql variable from the query results to use in the same query

I'd like to do the following query:

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

However, I can't seem to figure out how to put CHARINDEX('X', violations, 0) into a variable (VarX) so that I end up with something like:

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

I'm doing this to avoid running CHARINDEX twice.

Upvotes: 0

Views: 68

Answers (2)

David W
David W

Reputation: 10184

Try:

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

For the sake of illustration and somewhat less typing, one could (although most would likely frown on it):

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

Upvotes: 2

Joe Stefanelli
Joe Stefanelli

Reputation: 135888

Assuming SQL Server 2005+, you could use a 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;

Upvotes: 1

Related Questions