convert database table into XML schema file - sql-server

I am using SQL Server 2005. Is there any command or GUI tool (e.g. any menu/function from SQL Server management studio) to convert database table into XML schema file (.xsd)?
thanks in advance,
George

I've found this. Give it a try
Select CourseID, Name, CoursePrice
FROM CouseMaster.Course Course
FOR XML AUTO, XMLSCHEMA

You can write to file like this:
bcp.exe "select top 0 * from (select 1 as iCol) as t for xml auto, xmlschema" queryout outfile.xsd -T -c
I'm Using the TOP 0 to exclude the xml of the actual query data since you only want the schema. The -c causes it to be plain character data in the output, use -w instead if you want utf-16 (unicode) output.
EDIT - and if you want to change the xml structure, look at PATH with FOR XML.

Declare #SQL nvarchar(1000)
SET #SQL= 'bcp.exe '+ '"select * from yourdbname.yourschema.yourtablename for xml path (''record''), ROOT (''tabel'')"' +' queryout '+ 'c:\yourfilename.xsd' +' -w -r -t -SyourServerName -T'
print #SQL
EXEC Master..xp_CmdShell #SQL
Replace allvalues starts with 'your', accordingly

Related

Generate XML from SQL Server by select multiple tables to a certain file location

If I have following SQL statement which I can actually use to generate XML by the data from two tables. I got the results, but I have to right click it, click "Save As," then choose a location (e.g. C:\Users\my\Documents) for saving this XML. Is there a way to automate this?
SELECT
(SELECT y.* FROM dbo.TableY FOR XML PATH('y'), TYPE) AS 'YElements',
(SELECT a.* FROM dbo.TableA FOR XML PATH('a'), TYPE) AS 'AElements'
FOR XML PATH(''), ROOT('root')
You can use BCP, but you might have to enable XP_CMDSHELL using SP_CONFIGURE...
Furthermore there are some riddles to solve, as BCP has some rather weird attitudes (escaping characters, internal multiple quotes, fully qualified names...).
The main idea is:
Build a dynamic SQL statement to allow dynamically filled in pieces like a file name (but you might hardcode this...)
Execute the statement with xp_cmdshell
This will - at least - show you the general approach:
DECLARE #FileName VARCHAR(50)='C:\Users\...';
DECLARE #SQLCmd VARCHAR(2000)=
(
SELECT 'bcp.exe '
+ '"SELECT ''Just a test'' AS TestColumn FOR XML PATH(''''), ROOT(''root'')"'
+ ' queryout '
+ #FileName
+ ' -w -T -S ' + ##SERVERNAME
);
-- display command, for visual check
SELECT #SQLCmd AS 'Command to execute'
-- create the XML file
EXEC xp_cmdshell #SQLCmd;

Using BCP to create XML files produces files with invalid encoding for non-ASCII characters

Reproducing issue, SQL code:
CREATE TABLE dbo.FooTable(SomeString NVARCHAR(100));
INSERT INTO dbo.FooTable(SomeString)
VALUES('Degree symbol is °');
DECLARE #Code NVARCHAR(4000) = N'BCP "SELECT (SELECT SomeString FROM dbo.FooTable FOR XML PATH(''Foo''), ROOT(''BAR''), TYPE )" QUERYOUT "F:\Output\File.XML" -c -C RAW -T ';
EXEC xp_cmdshell #Code;
DROP TABLE dbo.FooTable;
It creates file with following content:
<BAR><Foo><SomeString>Degree symbol is °</SomeString></Foo></BAR>
Such files are not recognized as valid XML files by Internet Explorer and Firefox (Chrome yields error error on line 1 at column 23: Encoding error). If I open them with Notepad and save as Unicode (little endian) - it opens and validates.
Update:
changing bcp options to -T -w -r -t seems to make XML valid for most XML consumers, but not Internet Explorer.
Try this one -
IF OBJECT_ID('tempdb.dbo.##t') IS NOT NULL
DROP TABLE ##t
SELECT x = (
SELECT x
FROM (
VALUES (N'Degree symbol is °')
) t(x)
FOR XML PATH('Foo'), ROOT('BAR'), TYPE
)
INTO ##t
DECLARE #sql NVARCHAR(4000) = 'bcp "SELECT * FROM ##t" queryout "D:\sample.xml" -S ' + ##servername + ' -T -w -r -t'
EXEC sys.xp_cmdshell #sql
Just interesting where the root of your issue...

Exporting CSV's from SQL Server - Iterating different Key

I am currently going through the process of exporting a CSV file from an SQL Server DB for each unique key in a database that contains meter readings. I am doing this one at a time manually via Export data in SSMS.... It is making me want to die since I have 200 unique key values.
Here is my query:
SELECT DataTime, DataValue
FROM [i96X].[dbo].[PointValue]
WHERE PointID = 68352
The bulk of the query stays the same, the only value i change is the PointID. I need tab separated CSV's as output where the filename = the PointID.
Can someone help?
You can use xp_cmdshell and bcp to achieve what you want but it requires more privileges, in case you're thinking about running this in production.
You need to configure enable advanced options in order to enable xp_cmdshell and then enable xp_cmdshell
EXEC sp_configure 'show advanced options', 1 RECONFIGURE
EXEC sp_configure 'xp_cmdshell', 1 RECONFIGURE
Then we gather all PointIDs into a cursor so we can process individually
Declare curPointIDS Cursor For
Select Distinct PointID From [i96X].[dbo].[PointValue]
Open curPointIDS
Declare #pointId Int, #cmd Varchar(max)
Fetch Next From curPointIDS Into #pointId
While ##FETCH_STATUS = 0
Begin
Set #cmd = 'bcp "SELECT DataTime, DataValue FROM [i96X].[dbo].[PointValue] '
+ 'WHERE PointID = ' + LTRIM(#pointId) + '" queryout '
+ '"C:\Temp\Results_' + LTRIM(#pointId) + '.csv" -T -c -t,'
EXEC xp_cmdshell #cmd
End
Close curPointIDS
Deallocate curPointIDS
xp_cdshell: Runs commands in command prompt (https://msdn.microsoft.com/en-us/library/ms175046.aspx)
bcp: Sql Server's data extract utility https://msdn.microsoft.com/en-us/library/ms162802.aspx
Parameters:
-T: Use trusted connection
-c: Data type will be characters
-t: Specify delimiter, in this case it's comma (,)
You can use a loop and a temp table to accomplish this.
declare #i int = (select count(distinct PointID) from [i96X].[dbo].[PointValue])
select row_number() over(order by PointID) as rn, *
into #tmp --temp table
from [i96X].[dbo].[PointValue]
declare #id int
declare #sql varchar(4000)
while #i > 0
begin
set #id = (select PointID from #tmp where rn = #i)
SELECT DataTime, DataValue
FROM [i96X].[dbo].[PointValue]
WHERE PointID = #id;
select #sql = 'bcp "SELECT DataTime, DataValue FROM [i96X].[dbo].[PointValue] WHERE PointID = '+str(#id)+'" queryout "C:\Temp\'+str(#id)+'+'.csv'+'" -S servername -d databasename -U username -P password'
exec master..xp_cmdshell #sql
set #i = #i-1;
end
If you have a fix list of meters you can create a batch file and extract this information, on a regular basis, using the Task Scheduler.
Basically you should put on this batch file one row for each meter you want to extract and use sqlcmd to extract the historical records.
For example, let's say you want to extract the historical data for the pointIDs (1, 2, 3). You can create a batch file called "extract.bat" with the following lines:
sqlcmd -Q "select * from i96x.dbo.PointValue where Pointid=1" -s "\t" -o "C:\Results\1.csv"
sqlcmd -Q "select * from i96x.dbo.PointValue where Pointid=2" -s "\t" -o "C:\Results\2.csv"
sqlcmd -Q "select * from i96x.dbo.PointValue where Pointid=3" -s "\t" -o "C:\Results\3.csv"
You just need to run this batch file and get your files. This files will use tab as a column separator. If you want to use comma as column separator just change -s , on each row.
You can use excel to make easier to generate this batch file.
Another head up, with that query you will get ALL the values for each pointid. If you are working with meter probably you will be interested in extract only the last month. To do that you will need to adjust the query.

Export xml data using BCP Command in SQL Server

I am trying to export datable data in xml format but,Problem is like i can able to create xml file but data is not get writing in to the file following is my code I am trying.
DECLARE #cmd VARCHAR(2000);
SET #cmd = 'bcp.exe "select * from emp FOR XML AUTO" queryout E:\rahul_1.xml -x -T';
EXEC xp_cmdshell #cmd ;
And following is the output message I am getting after executing above code
NULL
Enter the file storage type of field XML_F52E2B61-18A1-11d1-B105-00805F49916B [ntext]:
can any body please suggest me on this
Dan you answer works, except one last thing. BCP needs additional information about the source query. Best idea to fully qualify the source of the data.
SET #cmd = 'bcp.exe "select * from [Database].[Schema].[Table] FOR XML AUTO"
queryout E:\rahul_1.xml -c -T';
Instead of the -x parameter (generate xml format file), specify -c (character file):
SET #cmd = 'bcp.exe "select * from emp FOR XML AUTO" queryout E:\rahul_1.xml -c -T';
Try to use -w switch for exporting XML file in correct format
DECLARE #cmd VARCHAR(2000);
SET #cmd = 'bcp.exe "select * from [Database].[Schema].[Table] FOR XML AUTO" queryout E:\filename.xml -S MyServer\MyInstance -c -T -w';
EXEC xp_cmdshell #cmd;

BCP utility creates trailing spaces when using FOR XML with TYPE specificed

I'm trying to export data from SQL server 2014 to an XML file. The file is however created with trailing spaces (65536 columns).
Please consider the following:
DECLARE #cmd VARCHAR(2000)
SET #cmd = 'BCP.EXE "SELECT * FROM (SELECT ''apple'' AS fruit UNION SELECT ''banana'' AS fruit) AS f FOR XML PATH(''''), ROOT(''fruits''), TYPE;" queryout "C:\dev\test.xml" -S ' + ##SERVERNAME + ' -c -CACP -r -t -T'
EXEC master.dbo.xp_cmdshell #cmd
When I do the same thing without TYPE directive, I don't get the trailing spaces. The query I have needs the TYPE directive specified.
How can the data be exported without the trailing spaces?
Can you remove your last TYPE directive? So instead of having:
XML PATH(''''), ROOT(''fruits''), TYPE
you would have
XML PATH(''''), ROOT(''fruits'')
It didn't change the XML structure but it did solve the trailing whispaces problem. Give it a try.

Resources