简体   繁体   中英

Export from Excel to SQL Server with Excel Column of Multiple Values

I am fairly new to database design although I have some SQL skill. I have an excel sheet that I wish to upload to SQL Server. The issue is I have a column in Excel that has multiple values separated by "/".

For example:

Fruit Banana/Pear/Orange Pear/Raspberry/... Banana

...

I want to split the cell based on "/" which I am fine doing. Then put the values into a table in SQL Server. However, there is no defined amount of "Fruits" that can be in the Excel cell so I need to allow for multiple table fields.

Does anyone have suggestions on how to do this? I wrote an ADODB connection to export from Excel to SQL Server but don't know how handle this cell.

Thank you

Another option is to split your data after it has been loaded. For example

Declare @YourTable table (ID int,Fruit varchar(150))
Insert into @YourTable values
(1,'Banana/Pear/Orange'),
(2,'Pear/Raspberry/Apple'),
(3,'Banana')


Select A.ID
      ,B.Key_Value
 From @YourTable A
 Cross Apply (Select * from [dbo].[udf-Str-Parse](A.Fruit,'/')) B

Returns

ID  Key_Value
1   Banana
1   Pear
1   Orange
2   Pear
2   Raspberry
2   Apple
3   Banana

The UDF

CREATE FUNCTION [dbo].[udf-Str-Parse] (@String varchar(max),@Delimeter varchar(10))
--Usage: Select * from [dbo].[udf-Str-Parse]('Dog,Cat,House,Car',',')
--       Select * from [dbo].[udf-Str-Parse]('John Cappelletti was here',' ')

Returns @ReturnTable Table (Key_PS int IDENTITY(1,1), Key_Value varchar(max))
As
Begin
   Declare @XML xml;Set @XML = Cast('<x>' + Replace(@String,@Delimeter,'</x><x>')+'</x>' as XML)
   Insert Into @ReturnTable Select ltrim(rtrim(String.value('.', 'varchar(max)'))) FROM @XML.nodes('x') as T(String)
   Return 
End

Use a Bridge Table . This way each row in Fruit table can have N types.

在此处输入图片说明

Description values in table Types will be Banana, Pear, Orange, Raspberry, etc.

When you design the table it will have to have a defined number of columns.

The simplest approach would be to assign an ID for each group.

ID  Fruit
1   Banana
1   Pear
1   Orange
2   Pear
2   Raspberry
3   Banana

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM