tags:

views:

46

answers:

5

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  A: 
SELECT SUBSTRING(col, 1, CHARINDEX(col,';'))
Chris McCall
+2  A: 
declare @t nvarchar(100) = 'Site=230;this=that;foo=bar;';
select convert(int, substring(@t,6, charindex(';',@t,0)-6))
Nestor
+1  A: 

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

jmucchiello
+1: this particular problem ought to be solved at a higher level: the datamodel.
BalusC
That is the way the vendor did it. I told them it sucks but I have to deal with it now.
-1 this is not a helpful answer
Chris McCall
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.
jmucchiello
A: 

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.

j.a.estevan
A: 

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.

Matt H