Export a SQL query to XML file - sql

I need to export a SQL query in SQL Server to an XML file.
So far, I have made ​​a query that is:
select *
from
products
for xml path ('product'), root ('Products');
With this query, the result is correct, but I have not found a way to export it to a file.
My idea is to make the export from SQL Management Studio, if possible.
If this option is not possible, I would like to give me a hand to find out what other options I can use.
The other options I've seen are SQLCMD and .NET with Visual Basic.

In Management Studio:
Run query as above.
Click on XML link in results - this will open the XML in a new window.
Navigate to new windown and File -> Save As - this should save as XML by default.
A bit of a manual process but maybe useful for an ad-hoc scenario?

For the sake of others who will be looking for this answer.
This can be achieved in two ways.
use EXEC xp_cmdshell and add queryout "Report.xml" in the syntax for it to save it as a xml file.
EXEC master.dbo.xp_cmdshell 'bcp "SELECT *FROM DataTable" queryout Report.xml -S[ServerName]
use sqlcmd tool. Like this,
just add save your query as input.sql:
sqlcmd -S <your-server> -i input.sql -o Report.xml

Related

How can i export the result set of an SQL Server stored procedure from one server into a table on another server?

I want to export the result set of an SQL stored procedure on one server into a table on another server. Is there a way I can do this?
Please help.
Sometimes using a Linked Server is also an option (I try to avoid them for several reasons), especially if you have enough permissions and if you need to do this as a one off. Then your code would simply look like:
INSERT INTO somelinkedservername.somedatabasename.dbo.sometable
EXEC dbo.thesproc
But pending on the size of the resultset I prefer to use BCP and a fileshare to keep it simple and put the code in a SQL Agent job for overview:
bcp.exe "EXEC [AdventureWorks].[dbo].[uspGetEmployees] #managerId = 666" queryout "\\SomeShare\Temp\emps.txt" -ServerA -T -c
And then
bcp.exe "\\SomeShare\Temp\emps.txt" in -ServerB -T -c
Server Objects > Linked Server > Right Click > New Linked Server
Data transfer= SELECT * FROM [Server Name].[Database Name].[Schema Name].[Table Name]
You can do something like this:
execute ('EXECUTE DatabaseName.Schema.ProcedureName #Parameter1=?,#Parameter2=?',#Parameter1Value,#Parameter2Value) at [ServerName]

Reading SQL script

Hi I am new to SQL scripts and have some problem to read below, especially for the symbols of N'USER11'and 'TV11man^%'. Could anybody interpret the statement including the symbols? Thanks a lot!
if not exists (select * from syslogins where loginname=N'USER11')
EXEC sp_addlogin 'USER11', 'TV11man^%', 'Lobby11'
If the USER11 entry does not exist, add login for USER11.
TV11man^% appears to be a password.
Normally % is a wildcard in SQL.
FYI.. Depending on your permissions, you can open the database:
select Programmability/Stored Procedures/System Stored Procedures
Locate sp_addlogin
Right-Click and choose modify
You will see what parameters are needed and what they mean,

exporting data from sql server into a CSV using ssms

I need to export data from several tables in SQL Server 2008 using SSMS. I do not want to use the native Export Data Wizard; I want to use a query instead. This means I cannot use sqlcmd or bcp.
How can I export data out of SQL Server 2008 using a query?
I need it to be comma delimited and double quoted as a text qualifier.
Thanks so much for any guidance/help.
You can easily create CSV output from SSMS, however it does not do quoting so you may want to choose a format like Tab delimited instead in step 6:
Open a new query window.
Create your SQL query.
Right click in the query window.
Choose Query Options...
Choose Text under Results.
Change the Output format: to Comma delimited.
Change the Maximum number of characters displayed in each column to 8000 or an appropriate value.
Click OK.
Right click in the query window.
Choose Results To and Results to File.
Execute your query.
Choose a file name and location.
Click Save.
You could run xp_cmdshell to run a bcp operation:
use [master];
declare #sql nvarchar(4000)
select #sql = 'bcp "select * from sys.columns" queryout c:\file.csv -c -t, -T -S'+ ##servername
exec xp_cmdshell #sql
You'd, of course, have to figure out how to format your qualifiers (probably through a format file)
EDIT:
Your source query would need to be something along the lines of:
SELECT IntValue + '"' + CharValue + '"' FROM TABLE
Also, you may need to have this feature enabled
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
GO
EXEC sp_configure 'xp_cmdshell', 1;
RECONFIGURE;
GO
Creating a text file using a SQL query is not possible. SQL is meant only for fetching,parsring,updating(etc) the data from the database. You need to have sytem executables/dlls to write to a file.
Is there a specific reason why you want to use a SSMS to export the results produced to a csv? Why don't you use SSIS to generate the results for a csv?
If you use SSIS to do this you create a package to export the information and then you schedule the package in a job to run when ever you want it to.
To export into an EXISTING excel file:
insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;',
'SELECT * FROM [SheetName$]') select * from SQLServerTable
This is dated, but I believe it is still valid.
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926
Cheers!
You could write a select spiced up with insert.
For instance:
select 'insert into TargetTable values(id, name) values ('''+ id +''','''+ name +''')' from SourceTable

Generating the stored procedures from command line

I want to generate Scripts i.e. Stored procedures and user defined functions from SQL server 2005. I have done it through SQL management studio but i want to to do it through Command line. Is there is any way to do it through command line arguments like sqlcmd.exe or any other scripting.
use sp_helptext with a query from SQLCMD
http://msdn.microsoft.com/en-us/library/ms176112.aspx
If you prefer something with a little more flexibility, check out the sys.sql_modules system view, as it gives you a bit extra information about the object and has the nice ability of being able to join to other system tables.
The rest of MauMen's answer is the right direction though: Use SQLCMD to generate the output to a file with the "-o OutputFile.sql".
For example, create a proc:
create proc dbo.pr_procDefTest
as
print 'This is a proc definition'
go
Show the definition:
select m.definition
from sys.procedures p
inner join sys.sql_modules m on p.object_id = m.object_id
where p.name = 'pr_procDefTest'
Output with SQLCMD:
sqlcmd -E -S .\sqlexpress -d test -o OutputFile.sql -Q "set nocount on; select m.definition from sys.procedures p inner join sys.sql_modules m on p.object_id = m.object_id where p.name = 'pr_procDefTest'" -h -1 -w 65535
There are a variety of paramaters passed in, which you can look up on the sqlcmd Utility MSDN page. The important thing to note is the use of "set nocount on;" in the beginning of the script to prevent the "(1 rows affected)" footer.
Microsoft released a new tool a few weeks ago called mssql-scripter that's the command line version of the "Generate Scripts" wizard in SSMS. It's a Python-based, open source command line tool and you can find the official announcement here. Essentially, the scripter allows you to generate a T-SQL script for your database/database object as a .sql file. You can generate the file and then execute it. This might be a nice solution for you to generate the schema and/or of your db objects such as stored procs. Here's a quick usage example to get you started:
$ pip install mssql-scripter
# script the database schema and data piped to a file.
$ mssql-scripter -S localhost -d AdventureWorks -U sa --include-objects StoredProcs --schema-and-data > ./myFile.sql
More usage examples are on our GitHub page here: https://github.com/Microsoft/sql-xplat-cli/blob/dev/doc/usage_guide.md

DB2 - How to run an ad hoc select query with a parameter in IBM System i Access for Windows GUI Tool

I would like to run some ad hoc select statements in the IBM System I Navigator tool for DB2 using a variable that I declare.
For example, in the SQL Server world I would easily do this in the SQL Server Management Studio query window like so:
DECLARE #VariableName varchar(50);
SET #VariableName = 'blah blah';
select * from TableName where Column = #VariableName;
How can I do something similar in the IBM System I Navigator tool?
I ran across this post while searching for the same question. My coworker provided the answer. It is indeed possible to declare variables in an ad hoc SQL statement in Navigator. This is how it is done:
CREATE OR REPLACE VARIABLE variableName VARCHAR(50);
SET variableName = 'blah';
SELECT * FROM table WHERE column = variableName;
DROP VARIABLE variableName;
If you don't drop the variable name it will hang around until who knows when...
At the moment, we're working on the same issue at work. Unfortunaly, we concluded that this is not possible. I agree, it would be great but it just doesn't work that way. iNavigator doesn't support SET or Define. You can do that in embedded SQL but this is not embedded SQL. Even if you create a separate document (xxx.sql), then need to open this document to run the script what makes it an interactive script (that is, DECLARE SECTION is not allowed).
As an alternative, in the SQL screen/script you can use CL:. Anything after this prefix is executed as CL command. You may manipulate your tables (e.g. RNMF) this way.
As a second alternative, the iSeries does support Rexx scripts (default installed with the os). Rexx is good dynamic script language and it does support embedded SQL. I've done that a lot of times and it works great. I even created scripts for our production environment.
Just create one 'default' script with an example PREPARE and CURSOR statement and copy at will. With that script you can play around. See the Rexx manual for the correct syntax of exec-sql. Also, you do have STDIN and STDOUT but you can use 'OVRDBF' to point to a database table (physical file). Just let me know if you need an example Rexx script.
Notice that the manual "SQL embedded programming" does have Rexx examples.
Here are a couple of other alternatives.
Data Transfer Tool - You can run the iSeries Data Transfer Tool from the command line (RTOPCB). First, run the GUI version and create a definition file. If you edit this file with a text editor, you will see that this is just an old-fashioned INI file and you can easily find the line with the query in it. From there, you could write a batch file or otherwise pre-process the text file to allow you to manipulate the query before submitting it to the query tool.
QSHELL - If you can log on to the iSeries interactively, then you may find the QSHELL environment more familiar than CL or REXX (although REXX is kind of fun). QSHELL is a full POSIX environment running on the iSeries. Use the command STRQSH to start QSHELL. You can have ksh or csh as a shell. Inside QSHELL, there is a command called "db2" that submits queries. So, you should be able to do something like this inside QSHELL:
system> VariableName = 'blah blah'
system> db2 "select * from TableName where Column = \'$VariableName\'"
You may have to fiddle with the quotes to get ksh to pass them correctly.
Also, inside QSHELL, you should have a full Perl installation that will allow you to use DBI to get data.
Some other ways to interact with data on the iSeries: query from the client with Python via ODBC; query from the client with Jython via JDBC; install Jython directly on the iSeries and then query via JDBC.