0

I have a row entry with the following format:

Site=[number];this=that;foo=bar;

[number] above can be from 1...infinity. So I need to split out the [number] to use in another select statements where clause. Site=[number] is always at the beginning in the string and the data is always separated by a semi-colon.

1
  • 2
    Is this string manipulation logic going in a select clause or a where clause? If it's going in a where clause, I would consider refactoring your database schema because you're unlikely to get good performance out of it. Commented Nov 5, 2009 at 23:07

5 Answers 5

2
declare @t nvarchar(100) = 'Site=230;this=that;foo=bar;';
select convert(int, substring(@t,6, charindex(';',@t,0)-6))
Sign up to request clarification or add additional context in comments.

Comments

1
SELECT SUBSTRING(col, 1, CHARINDEX(col,';'))

Comments

1

Why are you storing data in the database in this format? Split it up into columns so that you can do meaningful queries.

3 Comments

+1: this particular problem ought to be solved at a higher level: the datamodel.
That is the way the vendor did it. I told them it sucks but I have to deal with it now.
The original questioner didn't think I needed to be dinged but 3 months later, you did. Thank you for keeping stackoverflow safe, Chris McCall.
0

You can play with the string this way:

declare @tx as nvarchar(100)
set @tx = 'Site=[number];this=that;foo=bar;'

print substring(
    @tx, 
    CHARINDEX('[', @tx)+1, 
    CHARINDEX(']',@tx)-CHARINDEX('[',@tx)-1)

Hope this helps.

Comments

0

I don't have MS Sql Server available to try this out, but have you tried something like

Select field convert(bigint, substring(field, 6)) as thenum from thetable where condition=something

where field is the name of the field containing site=[number];...

The theory goes that substring will strip off site= off the beginning, and convert will (hopefully) convert the number portion and ignore the rest of the text from the semicolon onwards.

It may or may not work. If not you may need to write an elaborate function instead.

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.