I want to get all the fields from the table which i select in the query even if the fields contains no value(the value null or empty). the following is the query i have written.
SELECT (
SELECT T1.[CarrierCode_Destination] AS '#CarrierCode_Destination',
T1.[CarrierCode_Destination_Address] AS
'#CarrierCode_Destination_Address',
T1.[CarrierCode_Destination_Address1] AS
'#CarrierCode_Destination_Address1',
T1.[CarrierCode_Destination_Address2] AS
'#CarrierCode_Destination_Address2',
T1.[CIMtrek_RegContact] AS '#CIMtrek_RegContact',
T1.[CIMtrek_CarrierContact] AS '#CIMtrek_CarrierContact',
[T1].[CIMtrek_AdditionalContacts] AS
'#CIMtrek_AdditionalContacts'
FROM (
SELECT CD.[CIMtrek_DestinationName]
CarrierCode_Destination,
CD.[CIMtrek_DestinationAdd]
CarrierCode_Destination_Address,
CD.[CIMtrek_DestinationAdd_1]
CarrierCode_Destination_Address1,
CD.[CIMtrek_DestinationAdd_2]
CarrierCode_Destination_Address2,
CD.[CIMtrek_RegContact] CIMtrek_RegContact,
CD.[CIMtrek_CarrierContact] CIMtrek_CarrierContact,
CD.[CIMtrek_AdditionalContacts]
CIMtrek_AdditionalContacts
FROM CIMtrek_SystemTable_DatawareHouse CD
WHERE LEN(
LTRIM(
RTRIM(ISNULL(LTRIM(RTRIM(CD.[CIMtrek_DestinationName])), ''))
)
) != 0
) AS T1
FOR XML PATH('Record'),
TYPE
) FOR XML PATH('CarrierCode_Destination'),
TYPE
the results i get is
<CarrierCode_Destination>
<Record CarrierCode_Destination="8S - San Fran" CarrierCode_Destination_Address="SAN FRANCISCO - Redistribution" CarrierCode_Destination_Address1="4025 Whipple Road, " CarrierCode_Destination_Address2="Union City CA 94587" CIMtrek_RegContact="RDC San Francisco" />
<Record CarrierCode_Destination="8G - St Louis" CarrierCode_Destination_Address="ST. LOUIS - Redistribution" CarrierCode_Destination_Address1="126 Enterprise Drive, " CarrierCode_Destination_Address2="Wentzville MO 63385" CIMtrek_RegContact="RDC St Louis" />
<Record CarrierCode_Destination="V8 PHO/CYPR/CUST/TL " />
</CarrierCode_Destination>
but i want all the fields which are selected in the query. If you see the result it gives me the fields which are having value and omits the fields which don't have values.
how to do this, Please help.
Best Regards
If you use isnull() statements for each column you are selecting and convert null values to empty strings it should force the attributes to be generated for all columns. You may or may not also need to add rtrim() statements like I show below depending on if you have a datatype that is going to return a fixed size string:
SELECT (
SELECT rtrim(isnull(T1.[CarrierCode_Destination],'')) AS '#CarrierCode_Destination',
rtrim(isnull(T1.[CarrierCode_Destination_Address],'')) AS
'#CarrierCode_Destination_Address',
rtrim(IsNull(T1.[CarrierCode_Destination_Address1],'')) AS
'#CarrierCode_Destination_Address1',
rtrim(IsNull(T1.[CarrierCode_Destination_Address2],'')) AS
'#CarrierCode_Destination_Address2',
rtrim(IsNull(T1.[CIMtrek_RegContact],'')) AS '#CIMtrek_RegContact',
rtrim(IsNull(T1.[CIMtrek_CarrierContact],'')) AS '#CIMtrek_CarrierContact',
rtrim(IsNull([T1].[CIMtrek_AdditionalContacts],'')) AS
'#CIMtrek_AdditionalContacts'
FROM (
SELECT CD.[CIMtrek_DestinationName]
CarrierCode_Destination,
CD.[CIMtrek_DestinationAdd]
CarrierCode_Destination_Address,
CD.[CIMtrek_DestinationAdd_1]
CarrierCode_Destination_Address1,
CD.[CIMtrek_DestinationAdd_2]
CarrierCode_Destination_Address2,
CD.[CIMtrek_RegContact] CIMtrek_RegContact,
CD.[CIMtrek_CarrierContact] CIMtrek_CarrierContact,
CD.[CIMtrek_AdditionalContacts]
CIMtrek_AdditionalContacts
FROM CIMtrek_SystemTable_DatawareHouse CD
WHERE LEN(
LTRIM(
RTRIM(ISNULL(LTRIM(RTRIM(CD.[CIMtrek_DestinationName])), ''))
)
) != 0
) AS T1
FOR XML PATH('Record'),
TYPE
) FOR XML PATH('CarrierCode_Destination'),
TYPE
That worked for me when I tested it out but if you are also having issues with empty values not generating attributes you can first force all the empty values to be returned as NULL from the select against your original data table using NULLIF()
SELECT (
SELECT rtrim(isnull(T1.[CarrierCode_Destination],'')) AS '#CarrierCode_Destination',
rtrim(isnull(T1.[CarrierCode_Destination_Address],'')) AS
'#CarrierCode_Destination_Address',
rtrim(IsNull(T1.[CarrierCode_Destination_Address1],'')) AS
'#CarrierCode_Destination_Address1',
rtrim(IsNull(T1.[CarrierCode_Destination_Address2],'')) AS
'#CarrierCode_Destination_Address2',
rtrim(IsNull(T1.[CIMtrek_RegContact],'')) AS '#CIMtrek_RegContact',
rtrim(IsNull(T1.[CIMtrek_CarrierContact],'')) AS '#CIMtrek_CarrierContact',
rtrim(IsNull([T1].[CIMtrek_AdditionalContacts],'')) AS
'#CIMtrek_AdditionalContacts'
FROM (
SELECT NullIF(CD.[CIMtrek_DestinationName],'')
CarrierCode_Destination,
NullIF(CD.[CIMtrek_DestinationAdd],'')
CarrierCode_Destination_Address,
NullIF(CD.[CIMtrek_DestinationAdd_1],'')
CarrierCode_Destination_Address1,
NullIF(CD.[CIMtrek_DestinationAdd_2],'')
CarrierCode_Destination_Address2,
NullIF(CD.[CIMtrek_RegContact],'') CIMtrek_RegContact,
NullIF(CD.[CIMtrek_CarrierContact],'') CIMtrek_CarrierContact,
NullIF(CD.[CIMtrek_AdditionalContacts],'')
CIMtrek_AdditionalContacts
FROM CIMtrek_SystemTable_DatawareHouse CD
WHERE LEN(
LTRIM(
RTRIM(ISNULL(LTRIM(RTRIM(CD.[CIMtrek_DestinationName])), ''))
)
) != 0
) AS T1
FOR XML PATH('Record'),
TYPE
) FOR XML PATH('CarrierCode_Destination'),
TYPE
I normally use the following syntax:
SELECT *
FROM TABLE_NAME
WHERE FIELD_NAME = "CRITERIA"
Related
select distinct 'CART-data-map_val.role_name' as ProdMN
from VRN_544.RLT_001 AS mk_roles
JOIN VRMM.map_valxx AS map_val
ON ( Upper(Trim(map_val.role_name)) = Upper(Trim(mk_roles.rltx_02)) )
so, CART-data is the word which should append to the role_name into ProdMN column
ProdMN column Example - CART-data-map_val.role_name - 1- CART-data-reducer-role
2- CART-data-modular-role
how about using concat ?:
select distinct concat('CART-data-',map_val.role_name) as ProdMN
from VRN_544.RLT_001 AS mk_roles
JOIN VRMM.map_valxx AS map_val
ON ( Upper(Trim(map_val.role_name)) = Upper(Trim(mk_roles.rltx_02)) )
This is the section of my xml I am trying to modify:
<ORDER ORDER_NAME="10009999"
ORDER_NAME is an attribute.
This is what I have come up with so far and I think it's close, but slightly off.
update table_name set txn_message.modify('replace value of (/ORDER/#ORDER_NAME)[.=1000][1] with "2000"') , txn_status = 1
I want to replace 10009999 with 20009999 (really just something else to make it different so data can be reused, adding a additional character is also fine).
One way is
update t
set txn_message.modify('replace value of (/ORDER/#ORDER_NAME)[1] with concat("2", sql:column("vr"))')
from table_name t
cross apply (
select left(t.txn_message.value('(/ORDER/#ORDER_NAME)[1]','varchar(20)'), 1) vl
, substring (t.txn_message.value('(/ORDER/#ORDER_NAME)[1]','varchar(20)'), 2, 8000) vr
) v
where vl = '1';
Ive been banging my head against a wall with this for ages - and i've finally caved.
Can any SQL / XML experts please take a look at the below and tell me the best way to get the required XML format using FOR XML (raw? / Auto? / Path?) please?
Thanks for your help
Test data
CREATE TABLE #CustomerData(
[Customer ID] int
, IsCustomerID bit DEFAULT 1
, Amount1 float DEFAULT 0
, Amount2 float DEFAULT 0
)
INSERT #CustomerData
SELECT *
FROM (
VALUES (12345, 1, 50, 75),
(12444, 1, 100, 100),
(12455, 1, 25, 65)
) zz ([Customer ID], IsCustomerID, Amount1, Amount2)
Ive tried various combinations of FOR XML RAW / FOR XML PATH and FOR XML AUTO, but nothing quite matches.
<Root>
<Customers>
<Customer Prefix="Loan">
<Property Name="Customer ID" Value="REF_1234" IsCustomerId="True" />
<Property Name="Amount1" Value="10" />
<Property Name="Amount2" Value="15" />
</Customer>
</Customers>
</Root>
"Loan" is a hardcoded text flag to be applied to all entries from the above table, although there is no specific column for it.
"Customer ID"
"IsCustomerID"
"Amount1"
"Amount2"
Are all fields in a single table
A few things:
You do not specify where the value of Prefix comes from in your result, but for the query structure this doesn't matter.
FOR XML PATH allows you to conjure nested elements and attributes with specific syntax ('#' for properties) and specifying TYPE to insert the subqueries as typed XML.
T-SQL cannot dynamically pivot columns to rows (only statically), so you can't (easily) write a query to produce every individual column in its own child element except by writing out the columns explicitly. This is only a problem if you really do need dynamic output (i.e. the query must continue to include all columns without rewrites even if people add columns later).
Because of the downright peculiar syntax T-SQL uses to insert FLOAT and REAL values into XML (always using scientific notation) it's usually a good idea to either not use FLOAT/REAL at all but specific integral types (with CONVERT), or use FORMAT to produce a friendlier value. Likewise, a BIT value will always be output as 1 or 0, so if you need other values you'll need to provide for that yourself.
So:
SELECT (
SELECT
"#Prefix" = 'Loan',
(SELECT
"#Name" = 'Customer ID',
"#Value" = [Customer ID],
"#IsCustomerID" = CASE IsCustomerId WHEN 1 THEN 'True' ELSE 'False' END
FOR XML PATH('Property'), TYPE
),
(SELECT "#Name" = 'Amount1', "#Value" = FORMAT(Amount1, 'G') FOR XML PATH('Property'), TYPE),
(SELECT "#Name" = 'Amount2', "#Value" = FORMAT(Amount2, 'G') FOR XML PATH('Property'), TYPE)
FROM #CustomerData
FOR XML PATH ('Customer'), ROOT('Customers'), TYPE
)
FOR XML PATH('Root')
It is possible to factor out the repeated mention of Property by using a subquery that uses UNION ALL:
SELECT (
SELECT
"#Prefix" = 'Loan',
(
SELECT * FROM (
SELECT
"#Name" = 'Customer ID',
"#Value" = [Customer ID],
"#IsCustomerID" = CASE IsCustomerId WHEN 1 THEN 'True' ELSE 'False' END
UNION ALL
SELECT "#Name" = 'Amount1', "#Value" = FORMAT(Amount1, 'G'), NULL
UNION ALL
SELECT "#Name" = 'Amount2', "#Value" = FORMAT(Amount2, 'G'), NULL
) _
FOR XML PATH('Property'), TYPE
)
FROM #CustomerData
FOR XML PATH ('Customer'), ROOT('Customers'), TYPE
)
FOR XML PATH('Root')
I can see either of these forms being more or less readable/maintainable depending on what's likely to change.
I am trying to create a query that allows me to have the column name next to its column values that it finds.
As an example:
SELECT
*
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_NAME = 'saverTbl'
The above returns all of the column names in that table like this:
id, Link_userTblID, type, environment, vendor, theGUID, theGUID, etc etc...
Now what I need is to get the output from the table name next to the value. This is my query to just get my values from the table:
SELECT
*
FROM
saverTbl
WHERE
LINK_userTblID = #val1
The above returns the row that matches the LINK_userTblID like so:
32, 1, 'Blah', 'something', 'Adobe', 546656156-45332-54616516-4515, etc etc..
Now putting that all together (which is what this question is all about):
id: 32,
LINK_userTblID: 1,
type: Blah,
environment: something,
vendor: Adobe,
theGUID: 546656156-45332-54616516-4515,
etc etc.....
Pretty much needing the output in a json format but the column name matching up with the columns value.
Try this:
SELECT * FROM saverTbl
WHERE LINK_userTblID = #val1
FOR JSON PATH
Assuming, this is meant for one single row you can try this:
WITH cte AS
(
SELECT
(SELECT TOP 1 * FROM sys.objects FOR XML PATH('row'),TYPE) AS TheXml
)
SELECT TheElement.value('local-name(.)','nvarchar(max)')
+ ': '
+ TheElement.value('text()[1]','nvarchar(max)') AS YourOutput
FROM cte
CROSS APPLY TheXml.nodes('/row/*') AS A(TheElement);
The result:
YourOutput
---------------
name: sysrscols
object_id: 3
schema_id: 4
parent_object_id: 0
type: S
type_desc: SYSTEM_TABLE
create_date: 2012-02-10T20:15:58.693
modify_date: 2012-02-10T20:15:58.700
is_ms_shipped: 1
is_published: 0
is_schema_published: 0
XML in connection with XQuery and XPath is a very mighty toolset to solve rather generic problems. The cte builds an XML which looks like this:
<row>
<name>sysrscols</name>
<object_id>3</object_id>
<schema_id>4</schema_id>
<parent_object_id>0</parent_object_id>
<type>S </type>
<type_desc>SYSTEM_TABLE</type_desc>
<create_date>2012-02-10T20:15:58.693</create_date>
<modify_date>2012-02-10T20:15:58.700</modify_date>
<is_ms_shipped>1</is_ms_shipped>
<is_published>0</is_published>
<is_schema_published>0</is_schema_published>
</row>
The call to /row/* retrieves all nodes below <row> as derived table. The rest is rather easy XQuery.
I need to find a substring that is in a text field that is actually partially xml. I tried converting it to xml and then use the .value method but to no avail.
The element(substring) I am looking for is a method name that looks like this:
AssemblyQualifiedName="IPMGlobal.CRM2011.IPM.CustomWorkflowActivities.ProcessChildRecords,
where the method at the end "ProcessChildRecords" could be another name such as "SendEmail". I know I can use the "CustomWorkflowActivities." and the , (comma) to find the substring (method name) but not sure how to accomplish it. In addition, there may be more that one instance listed of the **"CustomWorkflowActvities.<method>"**
Some Clarifications:
Below is my original query. It returns that first occurrence in each row but no additional. For example I might have in the string '...IPM.CustomWorkflowActivities.ProcessChildRecords...' and
'...IPM.CustomWorkflowActivities.GetworkflowContext...'
The current query only returns Approve Time Process,
ipm_mytimesheetbatch,
ProcessChildRecords
SELECT WF.name WFName,
(
SELECT TOP 1 Name
FROM entity E
WHERE WF.primaryentity = E.ObjectTypeCode
) Entity,
Convert(xml, xaml) Xaml,
SUBSTRING(xaml, Charindex('CustomWorkflowActivities.', xaml) + Len('CustomWorkflowActivities.'), Charindex(', IPMGlobal.CRM2011.IPM.CustomWorkflowActivities, Version=1.0.0.0', xaml) - Charindex('CustomWorkflowActivities.', xaml) - Len('CustomWorkflowActivities.'))
FROM FilteredWorkflow WF
WHERE 1 = 1
AND xaml LIKE '%customworkflowactivities%'
AND statecodename = 'Activated'
AND typename = 'Definition'
ORDER BY NAME
If you are using Oracle you could use REGEXP function:
WITH cte(t) as (
SELECT 'AssemblyQualifiedName="IPMGlobal.CRM2011.IPM.CustomWorkflowActivities.ProcessChildRecords,' FROM dual
)
SELECT t,
regexp_replace(t, '.*CustomWorkflowActivities.(.+)\,.*', '\1') AS r
FROM cte;
DBFiddle Demo
SQL Server:
WITH cte(t) as (
SELECT 'AssemblyQualifiedName="IPMGlobal.CRM2011.IPM.CustomWorkflowActivities.ProcessChildRecords,asfdsa'
)
SELECT t,SUBSTRING(t, s, CHARINDEX(',', t, s)-s)
FROM (SELECT t, PATINDEX( '%CustomWorkflowActivities.%', t) + LEN('CustomWorkflowActivities.') AS s
FROM cte
) sub;
DBFiddle Demo 2