June 2009
Mon Tue Wed Thu Fri Sat Sun
« May   Jul »
1234567
891011121314
15161718192021
22232425262728
2930  

Day June 11, 2009

Splitting Strings in SQL

Let’s say that you have a column that contains some goofy data and it looks like this:

USA/Ohio
USA/Indiana
USA/Iowa
UK/Scotland
UK/England

So, how would you typically split such a string to only get the part after the ‘/’?

Well, here’s how I did it:

IF OBJECT_ID('tempdb..#tmp') IS NOT NULL
  DROP TABLE #tmp;
GO

CREATE TABLE #tmp
(
  s VARCHAR(255)
);
GO

INSERT INTO #tmp (s) VALUES
('USA/Ohio'),
('USA/Indiana'),
('USA/Iowa'),
('UK/Scotland'),
('UK/England');

SELECT SUBSTRING(s, CHARINDEX('/', s) + 1, LEN(s)) -- this is what does all the work
FROM #tmp;

But, apparently, there’s a simpler way:

SELECT PARSENAME(REPLACE(a, '/', '.'),1)
FROM #tmp;

It’s a bit hacky, but it works.

Basically, it takes advantage of the PARSENAME function to grab specific sections of a period delimited string, as it it were a SQL Server object.

Now you know. Paypal me some money if you find this useful and pass it off as your own work of genius.

Columbus PASS/SQL Server User Group Meeting Tonight!

This is just a quick reminder to everyone that CBusPASS (the Columbus, OH PASS Chapter) will be meeting tonight.

Details here, however the general gist is that Brent Ozar and I will be talking about using SQL Server Express edition in a presentation titled “Developing Something for Nothing”.

This site is protected with Urban Giraffe's plugin 'HTML Purified' and Edward Z. Yang's Powered by HTML Purifier. 226 items have been purified.