Select query changing content order - sql

I am using DB2 db, I have a table with one column containing xml, when I view the table in the data view of SQL Developer
<ns5:benefitComponent desc="Urgent Care Professional" level="2" name="UrgentCareProfessional">
now when i use a select query to fetch this, it changes to
<ns5:benefitComponent name="Acupuncture" level="1" desc="Acupuncture">
The order of the attributes changed am not sure why this happens, can anyone help me out?

DB2 stores an XML in a internal format, but it is stored according to the XML schema. Probably, your XML schema does not enforce an order. You should define the elements in a sequence in order to force the order.
http://www.w3schools.com/schema/el_sequence.asp

Related

How to remove Nulls from Save As in SQL Server Management Studio

I have created a variable that is type table inside a stored procedure. At the end of the procedure I am selecting all the rows in the table and displaying them. When I right click on the headers and select "Save As" it allows me to change the type to All Files and save the file as a text file. This works fine except that the columns that have NULLS in them saves as NULLS. I want it to fill NULLs in with spaces.
I've been trying to find a way to create a file using a stored procedure but most things indicate to use SSIS but I can't figure out how to use SSIS with a variable that is a table instead of using an actual table.
If I could either replace nulls with spaces or use a stored procedure to do the same thing it would be great. I can not use tab or comma delimited as the final product has to be a flat file that each column uses the same amount of characters as is declared in the column headers. Padded with spaces.
Thanks for any help you are able to offer.
Cheers
P.S. I am using SQL Server 2012 Management Studio
The easy way to do this would be to convert the NULLs to spaces in your SELECT statement.
SELECT COALESCE(yourcolumn, '')
Put the COALESCE clause around every column that has NULLs in it.
Using COALESCE article link
If the last thing you do in the stored procedure is Select * From TempTable then you can use that SP in an OleDb source component. Change from Table or View to Sql Command and use the Exec (sp_SomeName) syntax. This will create a pipe that you can connect to a destination component, such as flat file.
I have seen many issues over the years doing Save Results As... I will only use this for informal 'quick check' files and not for anything considered 'live' or 'production' data.
Here is a good blog that also shows how to use parameters.
http://geekswithblogs.net/stun/archive/2009/03/05/mapping-stored-procedure-parameters-in-ssis-ole-db-source-editor.aspx

Adding a Computed column with After clause

I am trying to create a computed column after a specified column.
But the SQL gives syntax error for the query below. Please help me with the correct syntax/way to do this.
ALTER TABLE service_ServiceClass
ADD LichenClassName AS ([dbo].[UfnGetServiceClassName]([Id])) AFTER Description
You get an error because "AFTER" is MySQL syntax.
There is no direct way to alter column order in SQL Server currently.
In MS SQL Server Management Studio, you'd have to use the SSMS Table Designer (rightclick yourTable->Design) to arrange your columns, which can then generate a script which drops and recreates the table.
There is no after clause in sql server's alter table statement.
The order of the columns in the table (as well is the order of the rows, btw) is completely insignificant from a user's point of view.
It's significant from the server point of view, as it may effect performance when using clustered indexes.
The only time the order of the columns matters is when you are using select * ..., but you shouldn't use that anyway. Always specify the column names directly.

Dynamically generated SQL security concerns (sql injection etc.)

We are in the process of developing an "API" for one of our products. This will allow the user to define which columns they wan't to return from their "queries" and we will build the needed SQL.
I know that you should always use parameterized queries to avoid SQL injection attacks. However is there any security risks when building a statement where the columns returned are defined by the users? Lets say we have the following api request. This is just an example to illustrate what I mean :)
/api/customers/getall?fields=Name,Phone,Email&where=Zip=1000
The SQL will be
SELECT Name, Phone, Email FROM Customers WHERE Zip = #Zip
I'm not thinking about just taking the fields parameter and building the SQL directly around that, it will probably be made into a list and returned with some default columns like Id and Modified.
What should you be aware of in this situation? And how would you protect against attacks?
-- Christian
Create a Stored Procedure
This will let you check the input Stings and you should be on the safe side.
See:
MSDN Create Stored Procedures
First, I do a query to get the fields of the selected table(s) from the INFORMATION_SCHEMA.COLUMNS metadata table.
Querying database metadata
The column names pulled from the database are safe to use. Then I compared the fields in the SELECT clause with the "safe fields list". If one of the selected fields isn't on the clean list, then remove it or don't run the generated SQL at all.

XML data type in SQL Server?

I have some unstructured data that describe setting for each devices. For e.g. for Device 1:
<ChartSetting xmlns="ChartSetting1">
<ChartSizeX>132.6</ChartSizeX>
<ChartSizeY>132.6</ChartSizeY>
<ChartType>Native</ChartType>
<BarSizeX>90</BarSizeX>
<BarSizeY>6</BarSizeY>
<DistToBar>34.8</DistToBar>
<DistToFirstLineY>17.5</DistToFirstLineY>
<MarkerDistance>120</MarkerDistance>
<DistToFirstField>18.5</DistToFirstField>
<PatchSizeX>7.5</PatchSizeX>
<PatchSizeY>9</PatchSizeY>
</ChartSetting>
However for Device 2 setting is different
<ChartSetting xmlns="ChartSetting2">
<PatchGap>1</PatchGap>
<PatchSize>5</PatchSize>
</ChartSetting>
xml data is not used for query purpose, it will be passed to the .net application that eventually send it to the devicedriver (through C++ code)
We only have four types device. So possibility of different settings is limited.
Can this kind of data be stored as typed XML that adhere to some schema? Storing as varchar will be nightmare if there are invalid settings stored.
I know xml schema collection can have multiple schema but can it confirms to only one schema.
Is there an easy way to create a schema?
Should I be using untyped XML instead?
You could create a DTD for the four different device types and validate your XML fragments with those DTDs, but I'd suggest you do that processing OUTSIDE of SQL Server.
If you are not going to query the XML, there isn't any reason to store it as the XML data type.
Answers to your questions:
Typed XML: you'll have to use a specific type per column (see http://msdn.microsoft.com/en-us/library/ms184277.aspx)
Create a
schema - check out (http://msdn.microsoft.com/en-us/library/ms176009.aspx) and try
something like XMLSpy if it gets too complex. Your snippets looked
small so I should think you can manage it with Notepad/++
I'd use untyped XML and validate it when it gets stored and/or retrieved
1.I think it's possible, if your schema collection contains 4 different schemas, the related column can contain xml that satisfies one of the schemas in collection.
2.I believe the easiest way is to let sql server create a schema for you (first create tables ChartSetting1,ChartSetting2 with desired columns - it's not necessarily, you can create SELECT that returns all columns, but using tables is easier), then
DECLARE #mySchema NVARCHAR(MAX);
SET #mySchema = N'';
SET #mySchema =#mySchema +
(
SELECT * FROM ChartSetting1
FOR XML AUTO, ELEMENTS, XMLSCHEMA('ChartSetting1')
);
SET #mySchema =#mySchema +
(
SELECT * FROM ChartSetting2
FOR XML AUTO, ELEMENTS, XMLSCHEMA('ChartSetting2')
);
CREATE XML SCHEMA COLLECTION [name] AS #mySchema;
-- we don't need these tables , drop them
DROP TABLE ChartSetting1,ChartSetting2
3.It depends. I'd say if you need constrain the XML data beyond schema validation, then it makes sense to use untyped XML. If schema validation covers all aspects of data validation, why not use it?
I think it is impossible create schema that conforms both XML.
Many XML editors can create XSD from XML, e.g.: Visual Studio
Typed XML vs. Untyped XML
XML shouldent really be stored in a databse as XML. XML is more of a transport medium than data. As you say its big and hard to query. You should store your data as data (varchar int ect) then use PATH MODE to return it back to you in the format you want

Changing Column Ordinal_position Positions

My scenario:
I can change the ordinal position of a column in a table.Is there a way to change the ordinal position of a column in a table without recreating the table?
No, you have to recreate the table if you wish to achieve this. (SQL SERVER)
Even when you do this in SSMS, you will see that the script that is generated also recreates the table.
Not in SQL Server - Not sure about other RDBMSs.
You can create a View with the desired ordinal positions but the only time I can think that would be useful is if you are using SELECT * which is a practice that should be avoided anyway.
Hi it depends on the database system you use.
For example in some it is possible to remove and add a column and you can do it in a procedure part where you also can refill it.
But in general it shouldn't matter as you can define the returned data order in your select statement. Is not that enough for you?
Without recreating the Table is Not possible. However, if your concern is about loosing the data here is an option provided by SQl Server Management Studio.
Note: I have used Sql Server 2019 Developer Edition.
Right Click on the Table name and Choose Design Option
Using your Cursor Drag the position of your Column to your desired Position
SQlServer Table Design Options
If you want to do it at script level, You can see the idea below provided by SSMS
Enable the "Auto Generate Change Script" Option available in Tools Menu --> Options --> Designers --> Table and Database Designers.
Enabling the Auto Generate Change Script Option
When you drag the Column in SSMS it will automatically creates the Script for you.
The High level Idea in the auto generated Script is,
Creating a Table with Temp_YourTableName with desired Order of Columns
Copying all the Data from the Original Table to new Temp_YourTableName
Drop the Original Table
Renaming the Temp_YourTableName to Original YourTableName
of course doing everything with Transaction scope to avoid any data loss while the script is executing.
I found a good reason why some time we need to do this here. Interestingly, it is based on Context and not to do anything with Technical.
Say for example, Original Address Table Contains, Street Address 1, City, State, Zip and Country columns. If the requirement Changes to include a new Columns like Street Address 2 this would be meaning full.