Getting error "Only one expression can be specified in the select list..." - sql

I am trying to add a column to a view with the following code:
SELECT ';' + CONTEXT as DriverNotes,
(STUFF((SELECT CustomerID FROM Notes E2 WHERE E2.CustomerID IN (Notes.CustomerID)
FOR XML PATH(''), TYPE, ROOT).value('root[1]','nvarchar(5)'),1,0,'')) as CustomerID FROM NOTES
On it's own it works just fine. When I run it within a View however, I get the following error:
"Only one expression can be specified in the select list when the subquery is not introduced with EXISTS."
I realize that the code here is trying to call two columns and that is what is giving me the error, but I only want one, and that would be CONTEXT. I need this to correlate with Notes.CustomerID but without the column appearing in the query.
I am still quite new to this, so any help would be greatly appreciated.

Check this query. I think this is what you want :
SELECT Notes.CustomerId,
STUFF(
(SELECT ';' + CONTEXT FROM Notes E2
WHERE E2.CustomerId = Notes.CustomerId
FOR XML PATH ('')), 1, 1, ''
) DriverNotes
FROM Notes /*Probably it should be Customer table */
GROUP BY Notes.CustomerId

Related

Data conversion or data mapping error HY000 in multi row concatenation in sub select in view

I have a sub-select as part of a view that generates a concatenated list of attributes from sub table. When doing a select from the view the data displays fine, but if it do a select in the concatenated list field I sometimes get the error Select or omit error on field.
AS400: V7R1M0
Main enitity:
MSGOCCID : CHAR 20
other fields.....
The detail entity fields (MSDPF):
MSGOCCID : CHAR 20
OCC : Integer 4
FIELDVAL : VARCHAR 128
I got the code for the sub select from StackOverflow and modified it for my situation. (I have also tried the recursive select but it very slow. The XMLSERIALIZE route is executable.)
To try and solve the problem it have added and removed REPLACE,COALESCE and TRIM of the value. I have added CCSID 1208 to the cast, changed the CHAR cast to VARCHAR... not change. (I have change CCSID 1208 to CCSID 37 at one stage to see if that will not solve it.)
If I run the select:
select MSGOCCID, COALESCE(DETLIST,' ')
from WBVIEW MSGP
where 1=1
If returns all the rows with not errors.
Sample output:
MSGOCCID: 2019020443165590
MSGDLIST: 14620, 1, C20180914023575582, 4179792C, C20180914023575582, 4179792C, WIPSTOCK, REMOVE, ROU07561
But if I use:
select MSGOCCID, COALESCE(DETLIST,' ')
from WBVIEW MSGP where 1=1 and DETLIST like '%4179792C%'
It fails with on the IBM backend:
Data conversion or data mapping error.
Select or omit error on field MapXmlData(Cast(Concat(',
',Strip(Replace(Cast(P6MSDPF_4.FIELDVAL AS VarChar(128) CCSID
1208),'-'), Both,' ')) AS VarChar(260) CCSID 1208)) member
COMMSWKBL1. Select/omit error on member COMMSWKBL1.
Short version of the view:
CREATE VIEW WBVIEW (
MSGOCCID ,
DETLIST )
AS
(SELECT MSG.MSGOCCID,
FROM P6DEVCDB00.P6MSGPF MSG
LEFT OUTER JOIN LATERAL
(SELECT XMLSERIALIZE(XMLAGG(XMLTEXT(CONCAT(', ',TRIM(REPLACE(REPLACE(REPLACE(FIELDVAL,',','-'),'>','-'),'<','-'))))) AS VARCHAR(4096) CCSID 1208) AS DETLIST
FROM MSDPF MSGDET
WHERE COALESCE(MSGDET.MSGOCCID,' ') != ' ' and
MSG.MSGOCCID = MSGDET.MSGOCCID AND
MSGDET.FIELDVAL != ''
GROUP BY MSGDET.MSGOCCID)MSGDLIST ON 1=1);
Character concatenation should not be a problem (except if it gets confused somewhere with the CCSIDs). I replace the <>, form the detail for in case that may interfere with xml functions... I have catered for Null and '' values ....
I have search lots of threads on lots of different sites and have run out of ideas.
Any suggestions will be appreciated.
I'm just guessing a quick comment answer here. Those left outer joins can introduce nulls into the mix you can simply coalesce them in the where clause ...
select MSGOCCID, COALESCE(DETLIST,' ')
from WBVIEW MSGP where
coalesce(DETLIST,' ') like '%4179792C%'
IRL I would use locate because it just feels faster when it runs.
select MSGOCCID, COALESCE(DETLIST,' ')
from WBVIEW MSGP where
locate('4179792C' ,coalesce(DETLIST,' ')) <> 0
HY000 is a CLI (ODBC) General error, the explaination in the IBM documentation is:
An error occurred for which there is no specific SQLSTATE and for which no implementation defined SQLSTATE is defined. The error message returned by SQLError in the argument szErrorMsg describes the error and its cause.
Since this is probably not something you are coding by hand, you probably do not have the opportunity to issue SQLError, but I suspect that the message you quoted in your question is the result of some internal process retrieving that error. so the problem should be:
Data conversion or data mapping error.
Select or omit error on field MapXmlData(Cast(Concat(',
',Strip(Replace(Cast(P6MSDPF_4.FIELDVAL AS VarChar(128) CCSID 1208),'-'), Both,' ')) AS VarChar(260) CCSID 1208)) member COMMSWKBL1. Select/omit error on member COMMSWKBL1.
I don't know your files, but I am guessing that there is bad data in the file and that COMMSWKBL1 is a select logical that is accessed to process the selection when you add the DETLIST like '%4179792C%' to your query. Your task is to find out which file is associated with member COMMSWKBL1, and see if you can determine why a Select or omit error would be occurring on that file.
It is fine. I have modified the view to select both the header and detail, and search on both entity entries (linked on the key MSGOCCID) and do a DISTINCT on the key MSGOCCID. It seems a little bit slower than the view the question is about but is working fine. Thank you for you time.

U-sql error: Expected one of: AS EXCEPT FROM GROUP HAVING INTERSECT OPTION ORDER OUTER UNION UNION WHERE ';' ')' ','

I have a following table:
EstimatedCurrentRevenue -- Revenue column value of yesterday
EstimatedPreviousRevenue --- Revenue column value of current day
crmId
OwnerId
PercentageChange.
I am querying two snapshots of the similarly structured data in Azure data lake and trying to query the percentage change in Revenue.
Following is my query i am trying to join on OpportunityId to get the difference between the revenue values:
#opportunityRevenueData = SELECT (((opty.EstimatedCurrentRevenue - optyPrevious.EstimatedPreviousRevenue)*100)/opty.EstimatedCurrentRevenue) AS PercentageRevenueChange, optyPrevious.EstimatedPreviousRevenue,
opty.EstimatedCurrentRevenue, opty.crmId, opty.OwnerId From #opportunityCurrentData AS opty JOIN #opportunityPreviousData AS optyPrevious on opty.OpportunityId == optyPrevious.OpportunityId;
But i get the following error:
E_CSC_USER_SYNTAXERROR: syntax error. Expected one of: AS EXCEPT FROM
GROUP HAVING INTERSECT OPTION ORDER OUTER UNION UNION WHERE ';' ')'
','
at token 'From', line 40
near the ###:
This expression is having the problem i know but not sure how to fix it.
(((opty.EstimatedCurrentRevenue - optyPrevious.EstimatedPreviousRevenue)*100)/opty.EstimatedCurrentRevenue)
Please help, i am completely new to U-sql
U-SQL is case-sensitive (as per here) with all SQL reserved words in UPPER CASE. So you should capitalise the FROM and ON keywords in your statement, like this:
#opportunityRevenueData =
SELECT (((opty.EstimatedCurrentRevenue - optyPrevious.EstimatedPreviousRevenue) * 100) / opty.EstimatedCurrentRevenue) AS PercentageRevenueChange,
optyPrevious.EstimatedPreviousRevenue,
opty.EstimatedCurrentRevenue,
opty.crmId,
opty.OwnerId
FROM #opportunityCurrentData AS opty
JOIN
#opportunityPreviousData AS optyPrevious
ON opty.OpportunityId == optyPrevious.OpportunityId;
Also, if you are completely new to U-SQL, you should consider working through some tutorials to establish the basics of the language, including case-sensitivity. Start at http://usql.io/.
This same crazy sounding error message can occur for (almost?) any USQL syntax error. The answer above was clearly correct for the provided code.
However since many folks will probably get to this page from a search for 'AS EXCEPT FROM GROUP HAVING INTERSECT OPTION ORDER OUTER UNION UNION WHERE', I'd say the best advice to handle these is look closely at the snippet of your code that the error message has marked with '###'.
For example I got to this page upon getting a syntax error for a long query and it turned out I didn't have a casing issue, but just a malformed query with parens around the wrong thing. Once I looked more closely at where in the snippet the ### symbol was, the error became clear.

TSQL parameter problems

I'm pretty new to SSRS reporting so bear with me.
When I run the report, the MONTH parameter has a problem if I select only one value from the multiple selections but if I select multiple values it works!
Anybody got any ideas as to why this is the case?
The error message says "An error has occurred during report processing (rsProcessingAborted)".
See TSQL coding below.
Thanks!
SELECT
rTranslog.[Month]
,rTranslog.Site
,rTranslog.NSVCode
,REPLACE(rProduct.LabelDescription, '!', ' ') AS [Drug]
,SUM(rTranslog.Qty) AS [Quantity]
,SUM(rTranslog.Cost/100) AS [CostIncVAT]
,SUM(rTranslog.CostExTax/100) AS [CostExVAT]
,rSpecialty.Description AS [SpecialtyDescription]
,rSpecialty.DirectorateCode
,rSpecialty.DivisionCode
,rSpecialty.CostCentre
FROM
rTranslog
INNER JOIN rProduct
ON rTranslog.NSVCode = rProduct.NSVCode
INNER JOIN rSpecialty
ON rTranslog.Specialty = rSpecialty.SpecialtyCode
GROUP BY rTranslog.Month, rTranslog.Site, rTranslog.NSVCode,
rTranslog.Specialty, rSpecialty.Description, rSpecialty.DirectorateCode,
rSpecialty.DivisionCode, rSpecialty.CostCentre,
REPLACE(rProduct.LabelDescription, '!', ' ')
HAVING Month IN (#Month) AND rSpecialty.Description IN
(#SpecialtyDescription) AND Site IN (#Site)
ORDER BY CostIncVAT DESC;

How can I run a SQL query iteratively for every row in a table?

I have the following query:
DECLARE #AccString varchar(max)
SET #AccString=''
SELECT #Acctring=#AccString + description + ' [ ] '
FROM tl_sb_accessoryInventory ai
JOIN tl_sb_accessory a on a.accessoryID = ai.accessoryID
WHERE userID=6
SELECT userID, serviceTag, model, #AccString AS ACCESSORIES FROM tl_sb_oldLaptop ol
JOIN tl_sb_laptopType lt ON ol.laptopTypeID = lt.laptopTypeID
WHERE userID=6
which outputs this:
What I want to be able to do is run this for every userID in a table tl_sb_user.
The statement to get the userIDs is:
Select userID from tl_sb_user
How can I get this to output a row as above for each user?
You are trying to do a string concatenation subquery. In SQL Server, you need to do the string concatenation using a correlated subquery with for xml path. Arcane, but it generally works.
The results is something like this:
SELECT userID, serviceTag, model, #AccString AS ACCESSORIES,
stuff((select ' [ ] ' + description
from tl_sb_accessoryInventory ai join
tl_sb_accessory a
on a.accessoryID = ai.accessoryID
where a.userId = ol.UserId
for xml path ('')
), 1, 11, '') as accessories
FROM tl_sb_oldLaptop ol JOIN
tl_sb_laptopType lt
ON ol.laptopTypeID = lt.laptopTypeID;
You don't have table aliases identifying where the columns come from, so I am just guessing that a.userId = ol.UserId references the right tables.
Also, this substitutes certain characters with html forms. Notably '<' and '>' turn into things like '<' and '>'. When I encounter this problem, I use replace() to replace the values.
Simply leave out the WHERE clause.

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.