Click here to Skip to main content
15,899,026 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hiii...

I have a table in sqlserver DB namely EmpSalary and it consists of following columns..

EmpID EmpName Jan13 Feb13 Mar13

It is being imported from an excel sheet through .aspx page using C# programming.

and now i want to insert another Excel Sheet into the same table ..

But now before inserting the new Excel sheet into the table, i want to delete all the old data present in the table and insert the new data.

or

I just want to check both old data and new data and append any new column(s) in the new data to the old data..

Like if the new data from excel has the following columns

EmpID EmpName Jan13 Feb13 Mar13 Apr13

then i want to append Apr13 column(along with data) to the old data in the EmpSalary table.

How to do this using C# programming.
Posted
Updated 19-Nov-13 20:05pm
v2
Comments
What have you tried?
Harsha24 20-Nov-13 5:44am    
thats a nice ques to ask..:)

I am able to insert excel sheet into the sql table.. my query is how to update it further..

OR

could u tel me how to import an excel along with colummns into sql table

1 solution

You probably need to check for the columns that don't exist first (doesn't matter if you only want the new data or the old data too):

SQL
IF EXISTS(SELECT column_id from sys.columns 
          WHERE Name = N'columnName' AND Object_ID = Object_ID(N'tableName'))
   BEGIN SELECT 1 END
ELSE
   BEGIN SELECT 0 END
Source[^]

You need to replace the 'tableName' and 'columnName' with the name of your table and the values of your excel columns accordingly.

You run the query for each column in you excel sheet and if it returns 0 you can add the column:

SQL
ALTER TABLE {TABLENAME} 
ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL} 

I don't know what type of data you got in your excelsheet you could try to map the values from the excel to an sql type. Just make sure that the values fit in the column ;)

If you want to delete the old data from the table just call a
SQL
DELETE FROM tablename
(just delete all the old data)

or
SQL
TRUNCATE TABLE tablename
(this basically recreates the table from scratch, resetting everything like index tables, auto increment values etc.)


You can then just start adding the new records (or update existing ones) with the values from your excel sheet.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900