Query value from XML data element - sql

I have a SQL query which returns data from a column. However the data in the column is in XML. I need value inside value element. How can I do so?
Please see my below SQL query.
SELECT
A.[business_line]
FROM
[EU_OTH_REG].[dbo].[TBL_EU_OTH_TXN_REG_RSDS] A
INNER JOIN
[EU_OTH_REG].[dbo].[TBL_EU_OTH_REG_MST_LOOKUP] B ON B.code = A.product_substance_type
The output to this query is
<collection><object parentid="ce57cc75-3966-478f-bf25-5e3abf716f96" parenttype="Object"><fields><field name="code"><value>BL2</value></field></fields></object></collection>
I want the value BL2 from this. The data is inside the value element. Can anyone help how to do so? I tried using stuff but I wasn't able to get the value.

XML.value() does the trick as follows:
declare #Test xml = '<collection><object parentid="ce57cc75-3966-478f-bf25-5e3abf716f96" parenttype="Object"><fields><field name="code"><value>BL2</value></field></fields></object></collection>';
select #Test.value('(/collection/object/fields/field/value)[1]', 'varchar(3)' )
Returns:
BL2
So add that to your query:
select A.[business_line].value('(/collection/object/fields/field/value)[1]', 'varchar(3)'
from [EU_OTH_REG].[dbo].[TBL_EU_OTH_TXN_REG_RSDS] A
inner join [EU_OTH_REG].[dbo].[TBL_EU_OTH_REG_MST_LOOKUP] B
on B.code = A.product_substance_type
As you have indicated that A.[business_line] is not of XML datatype, just convert it before calling value:
convert(xml, A.[business_line]).value
Note: I have assumed that its only ever a 3 character result i.e. varchar(3) but if not adjust to suit.

Related

Pentaho CDE SQL Query with numerical param

I would like to know if it is possible to perform an SQL query and pass it a numerical parameter. Let's suppose that I have the following query:
SELECT
CONCAT(cuatrimestre,' Cuatrimestre') As quarter
, ROUND(SUM(fact_Ventas.cantidad * precioUnitario),0) as amount
FROM fact_Ventas
INNER JOIN dim_Tiempos ON
fact_Ventas.idAnio = dim_Tiempos.idAnio AND
fact_Ventas.idMes = dim_Tiempos.idMes AND
fact_Ventas.idDia = dim_Tiempos.idDia
INNER JOIN dim_Clientes ON dim_Clientes.idCliente = fact_Ventas.idCliente
INNER JOIN dim_Productos ON dim_Productos.idProducto = fact_Ventas.idProducto
WHERE
CAST(fact_Ventas.idAnio As Char) LIKE ${paramAnio} AND
CAST(fact_Ventas.idMes As Char) LIKE ${paramMes} AND
CAST(fact_Ventas.idVendedor As Char) LIKE ${paramVendedores} AND
CAST(fact_Ventas.origen As Char) LIKE ${paramOrigen} AND
dim_Productos.marca LIKE ${paramMarca} AND
dim_Clientes.segmentoCliente LIKE ${paramSegmento}
GROUP BY 1
ORDER BY 1
I want to divide the column amount, by a numerical value extracted from a simple parameter. I managed to use filters in the where clause, but I can not make a division in a column.
Try the following query:
SELECT
CONCAT(cuatrimestre,' Cuatrimestre') As cuatrimestre
, ROUND( (SUM(fact_Ventas.cantidad * precioUnitario)/${paramValue}),0) as Importe
FROM fact_Ventas
INNER JOIN dim_Tiempos ON
fact_Ventas.idAnio = dim_Tiempos.idAnio AND
fact_Ventas.idMes = dim_Tiempos.idMes AND
fact_Ventas.idDia = dim_Tiempos.idDia
INNER JOIN dim_Clientes ON dim_Clientes.idCliente = fact_Ventas.idCliente
INNER JOIN dim_Productos ON dim_Productos.idProducto = fact_Ventas.idProducto
WHERE
CAST(fact_Ventas.idAnio As Char) LIKE ${paramAnio} AND
CAST(fact_Ventas.idMes As Char) LIKE ${paramMes} AND
CAST(fact_Ventas.idVendedor As Char) LIKE ${paramVendedores} AND
CAST(fact_Ventas.origen As Char) LIKE ${paramOrigen} AND
dim_Productos.marca LIKE ${paramMarca} AND
dim_Clientes.segmentoCliente LIKE ${paramSegmento}
GROUP BY 1
ORDER BY 1
But it gives an error and the data is not loaded. The syntax of the query was tested in the database and is correct.
Did you set the parameter type to Numeric? It defaults to String which was probably fine for your other parameters.
The problem was that I forgot to assign the parameter to the component, I had associated it with SQL Query but not with the component.

Teradata - Comparing Varchar to decimal

I am very new to Teradata and SQL in general. I need to create a table by combining data from three tables. I was able to successfully join two of them. I am not able to write the joining condition for the third table properly. Here is the code:
select s.cola, s.colb,
t.colc, t.cold,
u.cole, u.colf, u.colg, u.colh, u.coli, u.colj, u.colk, u.coll
from table1 s
inner join table2 t
on s.colb = t.colc
inner join table3 u
on t.cold = cast(u.colm as decimal)
order by 3
where substr(cast(s.cola as varchar(10)),6,2) = 11 and substr(cast(s.cola as varchar(10)),1,4) = 2017 and substr(cast(s.cola as varchar(10)),9,2) between 06 and 10
The error I am getting is:
[Teradata Database] [2620] The format or data contains a bad character.
I think the problem is with the line: on t.cold = cast(u.colm as decimal). The u.colm is of type VARCHAR(50) while t.cold is of type DECIMAL(10, 0). I believe I have casted it properly. Please help.Thanks in advance.
There's some bad data in u.colm.
Depending on your Teradata release you can check it using
WHERE u.colm > '' AND TRYCAST(u.colm as decimal(10,0)) ISNULL
or
WHERE u.colm > '' AND TO_NUMBER(u.colm) IS NULL
You can also use those in the join-condition, e.g.
on t.cold = trycast(u.colm as decimal(10,0))
Don't forget to add the precision of the decimal, as it defaults to (5,0).
Your WHERE_condition is strange, what's the datatype of s.cola?
Seems it's a string with a date yyyy-mm-dd in it. Try
WHERE trycast(s.cola as date) between date '2017-11-06' and date '2017-11-10'
Finally the ORDER BY should be placed after WHERE.

SQL Server: Conversion failed when converting the varchar value '1,2'

I have a query like this
select
t.tiid, t.employeeid, t.remarks,
dd.DocID, dd.Document, dd.DocuName
from
ti t
inner join
History cth on cth.tiid = t.tiid
inner join
Downloads dd on dd.DocID = cth.DocID
My data in table is like this
History:
DocID DocuName
1,2 abc.dox,def.docx
Downloads
DocID DocuName document
1 abc.docx x3400000efg..
2 def.docx xc445560000...
but when I execute this query, it shows an error:
Conversion failed when converting the varchar value '1,2' to data type int.
The DocID of history is multiple DocID had been combined with comma, So you can not compare the value directly( One value vs Multiple values).
You can check whether the multiple values contain the specify value use CHARINDEX.
To make sure complete matched of sub string,need a delimiter to indicate a single value, otherwise can get wrong result.
For Eample:
CHARINDEX('1,','12,2,3') will be 1, but in fact, there is no 1 in the string.
select
t.tiid,
t.employeeid,
t.remarks,
dd.DocID,
dd.Document,
dd.DocuName
from ti t
inner join History cth on cth.tiid=t.tiid
inner join Downloads dd on CHARINDEX(','+LTRIM(dd.DocID)+',',','+cth.DocID+',')>0
As the error says, you are trying to equate a string with int.You need to convert the int DocID as string and check if it's present in the comma-separated DocID .Something like
SELECT t.tiid,
t.employeeid,
t.remarks,
dd.DocID,
dd.Document,
dd.DocuName
FROM ti t
INNER JOIN History cth ON cth.tiid=t.tiid
INNER JOIN Downloads dd ON CHARINDEX(',' + CAST(dd.DocID AS VARCHAR(10)) + ',',',' + cth.DocID + ',')>0

Querying XML colum for values

I have a SQL Server table with an XML column, and it contains data something like this:
<Query>
<QueryGroup>
<QueryRule>
<Attribute>Integration</Attribute>
<RuleOperator>8</RuleOperator>
<Value />
<Grouping>OrOperator</Grouping>
</QueryRule>
<QueryRule>
<Attribute>Integration</Attribute>
<RuleOperator>5</RuleOperator>
<Value>None</Value>
<Grouping>AndOperator</Grouping>
</QueryRule>
</QueryGroup>
</Query>
Each QueryRule will only have one Attribute, but each QueryGroup can have many QueryRules. Each Query can also have many QueryGroups.
I need to be able to pull all records that have one or more QueryRule with a certain attribute and value.
SELECT *
FROM QueryBuilderQueries
WHERE [the xml contains any value=X where the attribute is either Y or Z]
I've worked out how to check a specific QueryRule, but not "any".
SELECT
Query
FROM
QueryBuilderQueries
WHERE
Query.value('(/Query/QueryGroup/QueryRule/Value)[1]', 'varchar(max)') like 'UserToFind'
AND Query.value('(/Query/QueryGroup/QueryRule/Attribute)[1]', 'varchar(max)') in ('FirstName', 'LastName')
You can use two exist(). One to check the value and one to check Attribute.
select Q.Query
from dbo.QueryBuilderQueries as Q
where Q.Query.exist('/Query/QueryGroup/QueryRule/Value/text()[. = "UserToFind"]') = 1 and
Q.Query.exist('/Query/QueryGroup/QueryRule/Attribute/text()[. = ("FirstName", "LastName")]') = 1
If you really want the like equivalence when you search for a Value you can use contains().
select Q.Query
from dbo.QueryBuilderQueries as Q
where Q.Query.exist('/Query/QueryGroup/QueryRule/Value/text()[contains(., "UserToFind")]') = 1 and
Q.Query.exist('/Query/QueryGroup/QueryRule/Attribute/text()[. = ("FirstName", "LastName")]') = 1
According to http://technet.microsoft.com/pl-pl/library/ms178030%28v=sql.110%29.aspx
"The XQuery must return at most one value"
If you are quite certain that for example your XML has let's say maximum 10 QueryRules you could maybe use WHILE to loop everything while droping your results into temporary table?
maybe below can help you anyway
CREATE TABLE #temp(
Query type)
DECLARE #i INT
SET #i = 1
WHILE #i >= 10
BEGIN
INSERT INTO #temp
SELECT
Query
FROM QueryBuilderQueries
WHERE Query.value('(/Query/QueryGroup/QueryRule/Value)[#i]', 'varchar(max)') LIKE 'UserToFind'
AND Query.value('(/Query/QueryGroup/QueryRule/Attribute)[#i]', 'varchar(max)') IN ('FirstName', 'LastName')
#i = #i + 1
END
SELECT
*
FROM #temp
It's a pity that the SQL Server (I'm using 2008) does not support some XQuery functions related to string such as fn:matches, ... If it supported such functions, we could query right inside XQuery expression to determine if there is any. However we still have another approach. That is by turning all the possible values into the corresponding SQL row to use the WHERE and LIKE features of SQL for searching/filtering. After some experiementing with the nodes() method (used on an XML data), I think it's the best choice to go:
select *
from QueryBuilderQueries
where exists( select *
from Query.nodes('//QueryRule') as v(x)
where LOWER(v.x.value('(Attribute)[1]','varchar(max)'))
in ('firstname','lastname')
and v.x.value('(Value)[1]','varchar(max)') like 'UserToFind')

SQL CONCAT IF Statement?

Morning All,
Im not to sure how i need to solve my following query... I have the following query which pulls back the desired records in SQL server...
SELECT agenda.AgendaItemNumber,Agenda.AgendaName, AgendaType.AgendaTypeDescription, userdetails.fullName
FROM Agenda
JOIN AgendaType ON AgendaType.AgendaTypeID=Agenda.AgendaTypeID
JOIN UserDetails ON Agenda.AgendaID = Userdetails.AgendaID
WHERE agenda.AgendaTypeID = '2'
AND AgendaItemNumber = AgendaItemNumber
AND AgendaName = AgendaName
AND AgendaTypeDescription = AgendaTypeDescription
AND AgendaItemNumber >= '3'
The above query works but i need to enhance this slightly. It pulls back the following results, which essentially are duplicate records except for the 'fullname' column...
What i would like to do is be able to add some extra code to this query so that when i run the query i am able to display one record for each 'AgendaItemNumber' and for it to concat both of the fullnames for this record. However i have additional AgendaItemsNumbers in this table that only have 1 x user fullname assigned to them. its just these few records within the image file i need to do something clever with.
Maybe there is a better way to complete this task?
Many thanks in advance. Any queries please dont hesitate to ask.
Regards
Betty
SELECT agenda.AgendaItemNumber,
Agenda.AgendaName,
AgendaType.AgendaTypeDescription,
STUFF(( SELECT ';' + FullName
FROM UserDetails
WHERE UserDetails.AgendaID = Agenda.AgendaID
FOR XML PATH('')
), 1, 1, '') AS fullName
FROM Agenda
INNER JOIN AgendaType
ON AgendaType.AgendaTypeID=Agenda.AgendaTypeID
INNER JOIN UserDetails
ON Agenda.AgendaID = Userdetails.AgendaID
WHERE agenda.AgendaTypeID = '2'
AND AgendaItemNumber = AgendaItemNumber
AND AgendaName = AgendaName
AND AgendaTypeDescription = AgendaTypeDescription
AND AgendaItemNumber >= '3'
ADENDUM
The XML extension in SQL-Server allows you to concatenate multiple rows into a single row. The actual intention of the extension is so you can output as XML (obviously), but there are some nifty tricks that are byproducts of the extensions. In the above query, if there were a column name in the subquery (FullName) it would output as <FullName>Joe Bloggs1</FullName><FullName>Joe Bloggs2</FullName>, because there is no column name it simply concatenates the rows (not forming proper XML). The PATH part allows you to specify an additional node, for example if you use PATH('Name') in the above you would get <Name>;Joe Bloggs</Name><Name>;Joe Bloggs2</Name> If you combine Path with a column name you would get Joe Bloggs.
Finally the STUFF just removes the semicolon at the start of the list.