SQL Import / Export Data [closed] - sql

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I've got a Windows Form App linked to a Microsoft SQL Server database with loads of tables.
I've got 2 buttons over there (Import and Export) and when clicking on EXPORT, this should trigger a Stored Procedure that will generate a string to export the data only (loads of INSERT statements - not the table definition). The string generated by this will be saved as a script file. This will be later used to IMPORT that data on to a different database.
I was thinking of creating a stored procedure to do this (but I'm not entirely sure how) or if there is a better approach for this, I'm open to any suggestions.

Use Management Studio to generate the script.
Right-click on the database in Object explorer, from context menu choose "tasks", then "generate scripts".
In the dialog, select the tables you want the data scripted out from. On the next page set the destination, and click on the "advanced" button. There find the "type of data to script" option - choose "data only".
[edit] As per the edited question, you can automate this using Microsoft.SqlServer.Management.Smo.Scripter, the same lib the SSMS uses.

If you want to generate a script that will generate an insert statement for you, you could build it with a query, like this...
SELECT
'SELECT ' + CAST(ID AS VARCHAR(10)) + ',''' +
VarcharField1 + ''',''' +
VarcharField2 + ''' UNION ALL'
FROM Example
If you display the results as text (Ctrl+T), you can easily grab it for further manipulation. It will generate something like this...
SELECT 1,'Row1Field1','Row1Field2' UNION ALL
SELECT 2,'Row2Field1','Row2Field2' UNION ALL
SELECT 3,'Row3Field1','Row3Field2' UNION ALL
SELECT 4,'Row4Field1','Row4Field2' UNION ALL
You would need to put an INSERT [TableName] before the results and trim the last UNION ALL, but this works. I've used it several times before. SQL Fiddle example

Related

How to read the value from EXCEL/CSV and pass into SQL query and the SQL query output also need to print in EXCEL/CSV

Input Excel/CSV:
SQL Query: -
select 'WWW' as COLUMN_NAME,
(case when to_char (max(WWW)) = to_char(min(WWW)) and to_char(count(WWW)) = count(*) or to_char(max(WWW)) is null then 'same' else 'diff'end)as COMPARISION_VALUE, to_char(max(WWW))as TRANSACTION1, to_char(min(WWW))as TRANSACTION2
from ABC
where Book ='123' and UPDATE_DATE='01-JUN-18';
Note: - I am looking to put this SQL query in loop where first row will pass into the SQL query, then it will check the 2nd row, if the cell is blank it will consider the top most value and COLUMN_NAME will iterate as much we have specified. All the above 4 columns should be parameter.
***Output Console: -***
COLUMN_NAME COMPARISION_VALUE TRANSACTION1 TRANSACTION2
WWW same test test
Expected Output: - I want to save all the transaction in excel/CSV one by one
Please find the attached doc for complete Details
Your question concatenates Excel/CSV as through they're the same thing. They are not. Excel is a very different thing from CSV. Consequently they are two different requirements.
Excel is a binary format which makes it hard to integrate with SQL (although there are third party libraries which can help). CSV is open and text-based, so it's a lot simpler. With an external table you can query a CSV using SQL. Find out more.
As for output, you've tagged your question [plsqldeveloper]. That is the tag for the Allround Automations IDE, which already has excellent capabilities for exporting to Excel or CSV. If you are using that tool you should not reinvent its features. Oracle SQL Developer also already does this (and I suspect TOAD and most of the other IDEs out there do too).

Copy all columns without data but with dependencies in SQL [duplicate]

This question already has answers here:
In SQL Server, how do I generate a CREATE TABLE statement for a given table?
(16 answers)
Closed 5 years ago.
So i'm trying to copy all data of table CarOrders into a new table, NewCarOrders. But i only want to copy columns and dependencies and not data. I don't know if it truly matters, but i'm using SQL Server Management Studio.
Here are two things that i tried, but none worked.
SELECT *
INTO NewCarOrders
FROM CarOrders
WHERE 0 = 1
The issue with above is, it is copying all the columns but it is not copying the dependencies/relationships.
I saw some posts on some of the forums regarding this, but the suggested solution was using SSMS Wizard. I want to do it using SQL (or T-SQL).
I'm new to SQL world, so i'm really sorry if it is a stupid or no brainer question. Let me know if i am missing some important information, i'll update it.
Try below query and check if this works for you
SELECT TOP 0 *
INTO NewCarOrders
FROM CarOrders
This will create NewCarOrders table with same structure as CarOrders table and no rows in NewCarOrders.
SELECT * FROM NewCarOrders -- Returns zero rows
Note : This will not copy constraints , only structure is copied.
For constraints do as below -
In SSMS right click on the table CarOrders, Script Table As > Create To > New Query Window.
Change the name in the generated script to NewCarOrders and execute.
Also change the constraints name in the generated script else it will throw error like There is already an object named 'xyz' in the database
You can use the like command:
CREATE TABLE NewCarOrders LIKE CarOrders;

display information from sql server view [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
New to views with sql server, not sure how to view the information it has gathered with vbscript. I know it is not as simple as:
select * from EXAMPLE_VIEW
I want to get the information from my example view loop through it and display it, however when i try to do that sql query i get invalid object name.
My question is how do you sql query a view
You should probably be doing this:
SELECT column1, column2 FROM dbo.EXAMPLE_VIEW;
This is because if your user has a different default schema than dbo, it might be checking for some other view with the same name under a different schema. (You also know not to use SELECT *, right?)
So you should also make sure your user account has select permissions on the view and/or the table(s) behind it.
Bad habits to kick : using SELECT * / omitting the column list
Bad habits to kick : avoiding the schema prefix
select * from EXAMPLE_VIEW
...is the correct way to query a SQL Server view.
If it's not working for you, you have a different kind of problem: maybe no permissions, maybe no server connection, maybe a view called EXAMPLE_VIEW doesn't exist, maybe something else.
Whatever it is - we need the exact error message and as much example code as possible to help you.
But the SQL itself is correct.
Is your current database set correctly after establishing connection? It can be set using connnection string (http://www.connectionstrings.com/) or by specyfying it witin query itself:
SELECT * FROM MYDB.dbo.EXAMPLE_VIEW;

Generating sql insert into for Oracle

The only thing I don't have an automated tool for when working with Oracle is a program that can create INSERT INTO scripts.
I don't desperately need it so I'm not going to spend money on it. I'm just wondering if there is anything out there that can be used to generate INSERT INTO scripts given an existing database without spending lots of money.
I've searched through Oracle with no luck in finding such a feature.
It exists in PL/SQL Developer, but errors for BLOB fields.
Oracle's free SQL Developer will do this:
http://www.oracle.com/technetwork/developer-tools/sql-developer/overview/index.html
You just find your table, right-click on it and choose Export Data->Insert
This will give you a file with your insert statements. You can also export the data in SQL Loader format as well.
You can do that in PL/SQL Developer v10.
1. Click on Table that you want to generate script for.
2. Click Export data.
3. Check if table is selected that you want to export data for.
4. Click on SQL inserts tab.
5. Add where clause if you don't need the whole table.
6. Select file where you will find your SQL script.
7. Click export.
Use a SQL function (I'm the author):
https://github.com/teopost/oracle-scripts/blob/master/fn_gen_inserts.sql
Usage:
select fn_gen_inserts('select * from tablename', 'p_new_owner_name', 'p_new_table_name')
from dual;
where:
p_sql – dynamic query which will be used to export metadata rows
p_new_owner_name – owner name which will be used for generated INSERT
p_new_table_name – table name which will be used for generated INSERT
p_sql in this sample is 'select * from tablename'
You can find original source code here:
http://dbaora.com/oracle-generate-rows-as-insert-statements-from-table-view-using-plsql/
Ashish Kumar's script generates individually usable insert statements instead of a SQL block, but supports fewer datatypes.
I have been searching for a solution for this and found it today. Here is how you can do it.
Open Oracle SQL Developer Query Builder
Run the query
Right click on result set and export
http://i.stack.imgur.com/lJp9P.png
You might execute something like this in the database:
select "insert into targettable(field1, field2, ...) values(" || field1 || ", " || field2 || ... || ");"
from targettable;
Something more sophisticated is here.
If you have an empty table the Export method won't work. As a workaround. I used the Table View of Oracle SQL Developer. and clicked on Columns. Sorted by Nullable so NO was on top. And then selected these non nullable values using shift + select for the range.
This allowed me to do one base insert. So that Export could prepare a proper all columns insert.
If you have to load a lot of data into tables on a regular basis, check out SQL Loader or external tables. Should be much faster than individual Inserts.
You can also use MyGeneration (free tool) to write your own sql generated scripts. There is a "insert into" script for SQL Server included in MyGeneration, which can be easily changed to run under Oracle.

How do you transfer or export SQL Server 2005 data to Excel

I have a simple SQL 'Select' query, and I'd like to dump the results into an Excel file. I'm only able to save as .csv and converting to .xls creates some super ugly output. In any case, as far as I can tell (using Google) this doesn't seem to be so straight forward. Any help would be greatly appreciated.
SSIS is a no-brainer for doing stuff like this and is very straight forward (and this is just the kind of thing it is for).
Right-click the database in SQL Management Studio
Go to Tasks and then Export data, you'll then see an easy to use wizard.
Your database will be the source, you can enter your SQL query
Choose Excel as the target
Run it at end of wizard
If you wanted, you could save the SSIS package as well (there's an option at the end of the wizard) so that you can do it on a schedule or something (and even open and modify to add more functionality if needed).
Use "External data" from Excel. It can use ODBC connection to fetch data from external source: Data/Get External Data/New Database Query
That way, even if the data in the database changes, you can easily refresh.
I've found an easy way to export query results from SQL Server Management Studio 2005 to Excel.
1) Select menu item Query -> Query Options.
2) Set check box in Results -> Grid -> Include column headers when copying or saving the results.
After that, when you Select All and Copy the query results, you can paste them to Excel, and the column headers will be present.
See this
This is by far the best post for exporting to excel from SQL:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926
To quote from user madhivanan,
Apart from using DTS and Export wizard, we can also use this query to export data from SQL Server2000 to Excel
Create an Excel file named testing having the headers same as that of table columns and use these queries
1 Export data to existing EXCEL file from SQL Server table
insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;',
'SELECT * FROM [SheetName$]') select * from SQLServerTable
2 Export data from Excel to new SQL Server table
select *
into SQLServerTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;HDR=YES',
'SELECT * FROM [Sheet1$]')
3 Export data from Excel to existing SQL Server table
Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;HDR=YES',
'SELECT * FROM [SheetName$]')
4 If you dont want to create an EXCEL file in advance and want to export data to it, use
EXEC sp_makewebtask
#outputfile = 'd:\testing.xls',
#query = 'Select * from Database_name..SQLServerTable',
#colheaders =1,
#FixedFont=0,#lastupdated=0,#resultstitle='Testing details'
(Now you can find the file with data in tabular format)
5 To export data to new EXCEL file with heading(column names), create the following procedure
create procedure proc_generate_excel_with_columns
(
#db_name varchar(100),
#table_name varchar(100),
#file_name varchar(100)
)
as
--Generate column names as a recordset
declare #columns varchar(8000), #sql varchar(8000), #data_file varchar(100)
select
#columns=coalesce(#columns+',','')+column_name+' as '+column_name
from
information_schema.columns
where
table_name=#table_name
select #columns=''''''+replace(replace(#columns,' as ',''''' as '),',',',''''')
--Create a dummy file to have actual data
select #data_file=substring(#file_name,1,len(#file_name)-charindex('\',reverse(#file_name)))+'\data_file.xls'
--Generate column names in the passed EXCEL file
set #sql='exec master..xp_cmdshell ''bcp " select * from (select '+#columns+') as t" queryout "'+#file_name+'" -c'''
exec(#sql)
--Generate data in the dummy file
set #sql='exec master..xp_cmdshell ''bcp "select * from '+#db_name+'..'+#table_name+'" queryout "'+#data_file+'" -c'''
exec(#sql)
--Copy dummy file to passed EXCEL file
set #sql= 'exec master..xp_cmdshell ''type '+#data_file+' >> "'+#file_name+'"'''
exec(#sql)
--Delete dummy file
set #sql= 'exec master..xp_cmdshell ''del '+#data_file+''''
exec(#sql)
After creating the procedure, execute it by supplying database name, table name and file path:
EXEC proc_generate_excel_with_columns 'your dbname', 'your table name','your file path'
Its a whomping 29 pages but that is because others show various other ways as well as people asking questions just like this one on how to do it.
Follow that thread entirely and look at the various questions people have asked and how they are solved. I picked up quite a bit of knowledge just skimming it and have used portions of it to get expected results.
To update single cells
A member also there Peter Larson posts the following:
I think one thing is missing here. It is great to be able to Export and Import to Excel files, but how about updating single cells? Or a range of cells?
This is the principle of how you do manage that
update OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\test.xls;hdr=no',
'SELECT * FROM [Sheet1$b7:b7]') set f1 = -99
You can also add formulas to Excel using this:
update OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\test.xls;hdr=no',
'SELECT * FROM [Sheet1$b7:b7]') set f1 = '=a7+c7'
Exporting with column names using T-SQL
Member Mladen Prajdic also has a blog entry on how to do this here
References: www.sqlteam.com (btw this is an excellent blog / forum for anyone looking to get more out of SQL Server).
If you are looking for ad-hoc items rather than something that you would put into SSIS. From within SSMS simply highlight the results grid, copy, then paste into excel, it isn't elegant, but works. Then you can save as native .xls rather than .csv
Here's a video that will show you, step-by-step, how to export data to Excel. It's a great solution for 'one-off' problems where you need to export to Excel:
Ad-Hoc Reporting
It's a LOT easier just to do it from within Excel.!!
Open Excel
Data>Import/Export Data>Import Data
Next to file name click "New Source" Button
On Welcome to the Data Connection Wizard, choose Microsoft SQL Server.
Click Next.
Enter Server Name and Credentials.
From the drop down, choose whichever database holds the table you need.
Select your table then Next.....
Enter a Description if you'd like and click Finish.
When your done and back in Excel, just click "OK"
Easy.
Create the excel data source and insert the values,
insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;',
'SELECT * FROM [SheetName$]') select * from SQLServerTable
More informations are available here
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926
You could always use ADO to write the results out to the worksheet cells from a recordset object
A handy tool Convert SQL to Excel converts SQL table or SQL query result to Excel file without programming.
Main Features
- Convert/export a SQL Table to Excel file
- Convert/export multiple tables (multiple query results) to multiple Excel worksheets.
- Allow flexible TSQL query which can have multiple SELECT statements or other complex query statements.
B. Regards,
Alex
There exists several tools to export/import from SQL Server to Excel.
Google is your friend :-)
We use DbTransfer (which is one of those which can export a complete Database to an Excel file also) here: http://www.dbtransfer.de/Products/DbTransfer.
We have used the openrowset feature of sql server before, but i was never happy with it, becuase it's not very easy to use and lacks of features and speed...
Try the 'Import and Export Data (32-bit)' tool. Available after installing MS SQL Management Studio Express 2012.
With this tool it's very easy to select a database, a table or to insert your own SQL query and choose a destination (A MS Excel file for example).
you can right click on a grid of results in SQL server, and choose save as CSV. you can then you can import this into Excel.
Excel gives you a import wizard, ensure you select comma delimited. it works fine for me when i needed to import 50k+ records into excel.
Check this.
Query -> Query Options.
Results -> Grid -> Include column headers when copying or saving the results