0

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.

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

4 Comments

Sorry, the example I had wasn't complete. I also need a bunch of columns from the same table other than the substring one.
Think you should be able to add them to the subselect and then pull them out into the main select.
Why would your second example be frowned on?
Well, select * constructs are generally not recommended because they return ALL the data from a table, so its preferable to select only the data that is needed. Reduces network traffic, exposes less information, things of that nature.
1

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.