Question

Create a SQL Table from a Dataset

Asked by: weinstein_josh

Has anyone out there created a new SQL table based off a given Dataset? Basically, I am importing an Excel file (which is supposed to have column heading in the first row) directly into a Dataset. From there, I would like to create a new table in SQL Server (with column names that match the Excel column headings in first row) and import the dataset into the table.

Also, any ideas on error handling and/or data validation would be helpful.

Thanks,
Josh

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2003-07-15 at 11:25:15ID20679383
Tags

from

,

table

,

create

,

dataset

Topic

.NET

Participating Experts
5
Points
0
Comments
22

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. dataset & vb.net & row order
    I have a dataset. One of the columns is "DIRECTORPositionheld". I need to move the row where DIRECTORPositionheld = "President" to the top of this dataset, before I bind it to a datalist object.
  2. Column Defaults with DataSet & SQL Server
    I have a simple question. Im trying to add a new row to a DataSet derived from an SQL Server query, however I am unable to figure out how to get the dataset to use the default column values as they are defined in SQL server. For instance, I have a bit column which by defaul...
  3. Insert DataSet into SQL Table
    I have a DataSet with a table that is identical in structure to a table in a SQL database. I am trying to insert this DataSet into my table in SQL. The table has 7 columns (col1, col2,...) Is there a simple way to do this without traversing through each record in my DataSe...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: iboutchkinePosted on 2003-07-15 at 11:40:54ID: 8927983

Did you try SQL statement Create table?

 

by: weinstein_joshPosted on 2003-07-15 at 11:49:49ID: 8928070

I was just trying to get some feedback as to the simplest way to do this (as the dataset has some update methods and such built in).  I realize I can dynamically create a SQL table by looping through the Dataset's table collection and create columns based on the first row of the Dataset.  Then just build up a dynamic CREATE TABLE string, and when complete, pass it to a sproc and execute the string as dynamic SQL.

Any code would be helpful though.

 

by: amit_gPosted on 2003-07-15 at 12:14:23ID: 8928269

The dataset doesn't have anything like that built in. You will have to do it yourself.

Shouldn't the table be already there and the web application only load the data in it?

 

by: weinstein_joshPosted on 2003-07-15 at 12:17:10ID: 8928299

No the table doesn't exist in SQL yet.  The user will upload an excel file to the server that they wish to create a table with.  From this excel file, I have imported it directly into a dataset.  From the dataset, I am trying to create a new SQL table based on the dataset and then import the dataset into the SQL table just created.

 

by: amit_gPosted on 2003-07-15 at 12:22:31ID: 8928341

Try DTS for this. You can make a DTS, save it in DB and then run it from the web page. Let us know if you want to use that and need help.

 

by: weinstein_joshPosted on 2003-07-15 at 12:30:46ID: 8928423

I thought about using DTS, but how can I create a DTS package that is dynamic to accept Excel files of different names and create the tablename accordingly?

I also thought about saving the DTS as a VB file and using that programatically somehow, but haven't started that direction.

 

by: amit_gPosted on 2003-07-15 at 12:44:20ID: 8928540

You could do that too but that would be much more complex. I and probably many others solve this by having same name for the Excel file. You said the file will be uploaded. After the upload is done, you can rename the file to the fixed file name and start the DTS.

I hope this is not a multi user application where many users will be uploading the files simultaneously. If it is this method will not work.

 

by: amit_gPosted on 2003-07-15 at 12:45:43ID: 8928554

Oh I am sorry, your destination table name is also not fixed. This will not work for you.

 

by: CarlosMuPosted on 2003-07-15 at 12:47:20ID: 8928577

Asuming that you have a store procedure with a table called Agent that has the following fields

            (client_src_sub_code,
             ap_code,
             agent_name_str,
             agent_ss_num,
              entity ,
             control_grp,
             ledger_key_1,
             ledger_key_2,
             ledger_key_3)


Create a store procedure with the following sintax


/* You only want to create the table the first time
You can also run the create table on a separate stored proceudure
*/

if Not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Agent]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
CREATE TABLE [dbo].[Agent] (
      [client_src_sub_code] [int] NOT NULL ,
      [control_grp] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
      [ap_code] [char] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
      [agent_ss_num] [numeric](18, 0) NULL ,
      [agent_name_str] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
      [entity] [varchar] (5) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
      [ledger_key_1] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
      [ledger_key_2] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
      [ledger_key_3] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
      [active_bol] [bit] NOT NULL
) ON [PRIMARY]
end

      INSERT INTO Agent
            (client_src_sub_code,
             ap_code,
             agent_name_str,
             agent_ss_num,
              entity ,
             control_grp,
             ledger_key_1,
             ledger_key_2,
             ledger_key_3)
      VALUES
            (@ClientSrcSub,
             @ap_code,
             @agent_name_str,
             @agent_ss_num,
              @entity ,
             @control_grp,
             @ledger_key_1,
             @ledger_key_2,
             @ledger_key_3)
END


Create a command object an associate this command to the InsertCommand of a dataAdapter. You should not need to
create Update and deletes commands because you are only going to  insert, but be prepare to create such commands with
stored procedures that do nothing, just in case.


Associate the parameters of the store procedure with the field on the dataset

insert the records in the dataset

run the update command of the dataadapter

 

by: CarlosMuPosted on 2003-07-15 at 12:50:43ID: 8928601

Sorry, I wrote the previous example before the message that indicate that destination table is not fixed.  
Instead of using stored procedures create a string with the corresponding sql statmente.  While you create
such a string you can asign the necesary table name.  The rest should work.

 

by: amit_gPosted on 2003-07-15 at 12:51:25ID: 8928609

Unless you want to rename the table after it has been created using sp_rename :)

Is it a muti user or single user system?

 

by: weinstein_joshPosted on 2003-07-15 at 12:58:49ID: 8928686

It is a multi-user application, but they won't be uploading excel files that often.  I really wanted to do it on the VB.NET end instead of relying on SQL to do it.  I am currently evaluating the option of saving a DTS package to a VB file and manipulating it, but I am not sure how well this will work to accomplish what I want.

 

by: amit_gPosted on 2003-07-15 at 13:24:55ID: 8928922

>> I can dynamically create a SQL table by looping through the Dataset's table collection

I would say, you already have a good approach. Build the CREATE TABLE statment dynamically the way you are thinking.

 

by: weinstein_joshPosted on 2003-07-15 at 13:27:11ID: 8928945

The only problem that I am having doing this is figuring out what data type to make the column dynamically.  That is one of the benefits of using the DTS, as it will do it for me.

Any suggestions?

 

by: amit_gPosted on 2003-07-15 at 13:55:05ID: 8929181

Even the DTS's guess is not good always as it is based on the first row only. How are you loading the Excel data in dataset? Can't you get the datatype from dataset tables? Worst scenario make them varchar(8000).

 

by: weinstein_joshPosted on 2003-07-15 at 13:59:10ID: 8929225

I am pretty sure I can get them programatically from the Dataset, but haven't ever done it before - trying right now.  I can't really make them Varchar(8000) b/c SQL's row size limit for a table is a total of 8000 bytes, so any insert into this table with multiple columns of Varchar(8000) would cause some problems.

 

by: amit_gPosted on 2003-07-15 at 14:22:49ID: 8929431

Check out DataType and MaxLength properties of DataColumn class. You will still need to do some mapping as the DataType returns .NET datatype not the SQL datatype.

The limit is on actual size. Since varchar doesn't allocate the space unless there is a data in it, you can have as many columns of this size. Yes, the total size of the row data can not exceed 8k but that limitation is always there whatever way the table is created. As I said earlier, it is the worst scenario solution - not a good one. So don't use it unless you have to.

 

by: weinstein_joshPosted on 2003-07-16 at 11:20:05ID: 8936838

How about taking this a different direction.

I was able to create a XML Schema document (.xsd) and a XML file containing the records from my dataset.  Is there any T-SQL commands that I can use to create a new table directly from the .xsd file and then import the XML file?

 

by: iboutchkinePosted on 2003-07-16 at 12:35:17ID: 8937358

maybe you will keep everything in XML and don't need extra table?

 

by: weinstein_joshPosted on 2003-07-22 at 11:45:21ID: 8979358

If anyone cares, I figured out how to do it and am posting it for others:

Dim myDataType As String = ""
                Dim myDataTypeLength As Integer
                Dim myColumnName As String = ""
                Dim myDataColumn As DataColumn
                Dim CreateTableString As String = "CREATE TABLE " & TableName & "("
                Dim CreateColumnString As String = ""

                With myDataTable.Rows(0)
                    For Each myDataColumn In myDataTable.Columns
                        myColumnName = myDataColumn.ColumnName.ToString
                        myDataType = myDataColumn.DataType.ToString
                        Select Case myDataType
                            Case Is = "System.Double"
                                myDataType = "FLOAT"
                            Case Is = "System.Decimal"
                                myDataType = "FLOAT"
                            Case Is = "System.String"
                                myDataType = "VARCHAR(1000)"
                            Case Is = "System.DateTime"
                                myDataType = "DATETIME"
                            Case Else
                                myDataType = "VARCHAR(500)"
                        End Select
                        CreateColumnString += myColumnName & " " & myDataType & ", "
                    Next myDataColumn
                End With

                CreateColumnString = CreateColumnString + ")"
                CreateColumnString = Replace(CreateColumnString, ", )", ")")
                CreateTableString = CreateTableString & CreateColumnString

                'Make sure table doesn't already exist
                strSQL = "if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[" & TableName & "]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[" & TableName & "] "
                app.ExecSQL(strSQL)
                'Create the new table
                strSQL = "EXEC ExecuteSQL '" & CreateTableString & "', '" & TableName & "'"
                app.ExecSQL(strSQL)

 

by: TheLearnedOnePosted on 2003-12-08 at 08:29:30ID: 9897381

No comment has been added lately, so it's time to clean up this TA.
I will leave the following recommendation for this question in the Cleanup topic area:

PAQ with points refunded

Please leave any comments here within the next seven days.
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

TheLearnedOne
EE Cleanup Volunteer

 

by: PashaModPosted on 2003-12-08 at 13:13:08ID: 9899530

Question closed and points refunded

PashaMod
CS Moderator

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...