0

I'm trying to import data from an excel spreadsheet into a SQL Server 2008 database and I need to massage the data a bit first.

I've used the Data Import wizard to load it into a staging table in the database in the following format:

Id  ISOCode  Data
1   US       Foo
2   CA       Bar
3   US or CA Blah

In cases where ISO is an OR-delimited string, eg US or CA, I need to split it into 2 rows, so in the final destination table it would look like this:

Id  ISOCode  Data
1   US       Foo
2   CA       Bar
3   US       Blah
3   CA       Blah

I do have a SplitString table-valued function available but I'm not sure how to work it into the equation.

4

2 回答 2

2

Here is my solution:

SELECT ID, 
   CASE 
     WHEN ( ISOCODE LIKE '% or %' ) THEN LEFT(ISOCODE, Charindex('or', 
                                                       ISOCODE) - 1 
                                         ) 
     ELSE ISOCODE 
   END AS ISOCode, 
   DATA 
FROM   TBL 
UNION 
SELECT ID, 
       RIGHT(ISOCODE, Len(ISOCODE) - ( Charindex('or', ISOCODE) + 2 ))AS ISOCode 
       , 
       DATA 
FROM   TBL 
WHERE  ISOCODE LIKE '% or %' 

You can take a look at the full solution (with data) on SQL Fiddle.

于 2012-10-11T13:05:22.480 回答
0
select t.Id, c.ISOCode, t.Data
from t
cross apply (select charindex(' or ', t.ISOCode) as OrIndex) idx
cross apply
(
  select t.ISOCode where idx.OrIndex = 0
  union all select left(t.ISOCode, idx.OrIndex - 1) where idx.OrIndex > 0
  union all select substring(t.ISOCode, idx.OrIndex + 4, len(t.ISoCode) - idx.OrIndex - 3) where idx.OrIndex > 0
) c

(this query doesn't require 2 table scans)

于 2012-10-11T13:58:14.500 回答