SQL Server 2005 FOR XML Clause - sql

We are having an issue where we are running the exact same query on two different servers, running the exact same service pack and update - 9.0.4211 - but receiving two differently formatted XML resultsets. Does anyone have any idea why/how this is happening?
Is there a setting/schema involved somehow in the way SQL Server generates the resulting XML format? I understand that we can transform the xml with the PATH option but at this point all of the client code is written to use the format from one of the result sets and using the path options still does not get us what the AUTO option does for the correct format.
Query -
SELECT distinct
operation.operationid,
#zoneId as ZoneID,
member.name, IsNull(member.firstname, '') as firstname, IsNull(member.lastname, '') as lastname, IsNull(member.email, '') as email, IsNull(member.memberid, '') as memberid, IsNull(member.type, '') as type, IsNull(member.AppMemberID, '') as AppMemberID
FROM IQSECURE_TaskOperations operation
join IQSECURE_RoleTasks r on operation.taskid = r.taskid
join IQOBASE_Rosters roster on r.roleid = roster.roleid
left outer join IQObase_Members member on roster.rosterid = member.Rosterid
WHERE operation.operationid = #operationid AND roster.zoneid = #zoneId and member.memberid is not null
union
SELECT distinct
operation.operationid,
#zoneID as ZoneID,
member.name, IsNull(member.firstname, '') as firstname, IsNull(member.lastname, '') as lastname, IsNull(member.email, '') as email, IsNull(member.memberid, '') as memberid, IsNull(member.type, '') as type, IsNull(member.AppMemberID, '') as AppMemberID
FROM IQSECURE_TaskOperations operation
join IQSECURE_RoleTasks r on operation.taskid = r.taskid
join IQOBASE_Rosters roster on r.roleid = roster.roleid
left outer join IQOBASE_Members_Exploded member on roster.rosterid = member.Rosterid
WHERE operation.operationid = #operationid AND roster.zoneid = #zoneid and member.memberid is not null
ORDER BY IsNull(member.type, ''), IsNull(member.lastname, ''), IsNull(member.firstname, ''), member.name
FOR XML AUTO, XMLDATA
Returned xml can be provided if need be.
Thanks in advance for any help provided.
Jon

You can check if there are any differences on the database:
SELECT *
FROM sys.configurations
ORDER BY name ;
And I would also check the client you are using. If you are using SQL Management Studio there is a menu option Tools / Options. This has setting that might affect what you are seeing.

This problem was a two part problem. The two databases were not exactly the same, one had SQL 2000 compatibility mode the other SQL 2005. The one with SQL 2000 was generating the correct XML format. So, one fix was to make the other SQL 2000 compatible. The other solution was to rewrite the select without the UNION. For some reason the UNION caused the incorrect XML format.

Related

GTFS - all services for particular stop

Crucial functionality of my app is to search bus stops by name which will return bus stop details as well as all services departing from it. I used php and MySQL and I was able to do so using GROUP_CONCAT. Now I'm planing to move to MS SQL and I did some initial work on this. I'm able to get all needed information using stored procedure like this:
SELECT Id, Name, Latitude, Longitude, Url,
(SELECT [dbo].[RoutesForStopId](Id)) 'Routes'
FROM Stops WHERE Stops.Name LIKE '%' + #Parameter + '%'
Where RoutesForStopId is scalar-valued function:
SELECT #Routes = STUFF((
SELECT DISTINCT ',' + r.ShortName FROM StopTimes st
INNER JOIN trips t ON t.TripId = st.TripId
INNER JOIN routes r ON r.Id = t.RouteId
WHERE st.StopId = #StopId
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM Stops WHERE Stops.Id = #StopId
It works as expected but response is very slow. I often get timeouts when calling this service.
Is there any way to speed up this query? I would appreciate a help on this as this is important piece of information for end user but being this slow I'm considering to get rid of this. It used to work much faster with MySQL db.
Thanks

SQL - Cannot find either column "c" or user-defined function or aggregate "c" or the name is ambiguos

I'm not really good in SQL and I did some searching and couldn't really figured it out how to use STUFF. I mean it looks simple but when I use it, there's always an error.
Anyway, here is the portion of my code and I just want to combine 2 printer of the rows with the same computer name pulled from database, honestly I'm not even sure if I'm doing it right but please do correct me if I'm wrong. Really need the professionals to guide me and do let me know if the information is not sufficient. Thanks in advance.
Update:
Added more code, and I didn't mention clearly, my query is pulling different data from multiple tables. It may be a bit messy but it got what I wanted, my problem is combining the printer result.
SELECT DISTINCT sc.ComputerName AS 'Computer name',
*
*
*
ISNULL(c.PrinterName <-- error on this c.printername
(
STUFF
((
SELECT
'; ' + c.PrinterName
FROM PrinterList AS c
WHERE c.ComputerName = sc.ComputerName
FOR XML PATH(''), TYPE).value('.','nvarchar(max)'), 1, 2,'')), '') AS 'Printer'
FROM Computer sc
Full Join PCInfo AS a
ON a.ComputerName = sc.ComputerName
Full Join DriverList AS b
ON b.ComputerName = sc.ComputerName
Full Join PrinterList AS c
ON c.ComputerName = sc.ComputerName
WHERE RTRIM(LTRIM(REPLACE(lower(sc.ComputerName), ' ',''))) like '%example%'
The c alias is only available in the namespace of the subquery, but you do not reference it from there.
I would expect something like this:
SELECT c.PrinterName,
STUFF( (SELECT '; ' + c.PrinterName
FROM PrinterList AS c
WHERE c.ComputerName = sc.ComputerName
FOR XML PATH(''), TYPE
).value('.', 'nvarchar(max)'
), 1, 2, '')
) as printers
FROM computer c ;
There is no need for the join in the outer query. I also don't see why an outer join would be desired.

Combine 2 XML Output Statements into one XML file

I've been working on outputting from SQL to XML and have finally come up with 2 queries that work fabulously for what I need with one problem. I did these independently as I am a novice with XML and now I need to combine them into one file for output. What I have is pretty complicated using dynamic SQL so I'm just going to post the dynamic part and exclude all of the variable and un-pivoting stuff I'm doing at the beginning. If I could just get result set 1 to be at the top and result set 2 just below it would suffice. I would like a wrapper tag (not sure if that's the term) as the very first and very last lines in this file. I'm not sure if anyone can tell me what I'm doing wrong just by looking at the dynamic code but I thought it would be worth a try. As I said, both of these work great but produce 2 separate files. Thanks in advance!
EXEC ('
SELECT
(SELECT GETDATE() AS STARTDATE,
GETDATE() AS ENDDATE
FOR XML PATH(''RECDATE''),ELEMENTS, TYPE),
(SELECT COUNT(*) AS SURVEY_COUNT
FROM PM_TEMP.dbo.tmpKansasCancerCenterExtract FOR XML PATH(''''), ELEMENTS, TYPE),
(SELECT ''PEPM'' as SERVICE,
DataCol as VARNAME,
Question as QUESTION_TEXT,
AnswerValue as ANSWER_TEXT
from PM_TEMP.dbo.tmpKansasCancerCenterCodeSheetExtract FOR XML PATH(''QUESTION''), ROOT(''QUESTION_MAP''), ELEMENTS, TYPE)
FOR XML PATH(''HEADER'')
SELECT PATID,CLIENTID,SERVICE,PATVISITDT,DATE,
(
SELECT VarName,Value
FROM PM_TEMP.dbo.tmpKansasCancerCenterExtract_AnalysisPivot P
INNER JOIN PM_TEMP.dbo.tmpKansasCancerCenterExtract E ON E.PatVisitID = P.PatVisitID
FOR XML PATH(''Response''), TYPE, ROOT(''Analysis'')
),
(
SELECT VarName,Value
FROM PM_TEMP.dbo.tmpKansasCancerCenterExtract_DemoPivot P
INNER JOIN PM_TEMP.dbo.tmpKansasCancerCenterExtract E ON E.PatVisitID = P.PatVisitID
FOR XML PATH(''Response''), TYPE, ROOT(''Demographics'')
)
FROM PM_TEMP.dbo.tmpKansasCancerCenterExtract
FOR XML PATH(''PatientLevelData''),TYPE, ROOT(''PatientLevelData'')
')

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 Server Compact won't allow subselect but inner join with groupby not allowed on text datatype

I have the following sql syntax that I used in my database query (SQL Server)
SELECT Nieuwsbrief.ID
, Nieuwsbrief.Titel
, Nieuwsbrief.Brief
, Nieuwsbrief.NieuwsbriefTypeCode
, (SELECT COUNT(*) AS Expr1
FROM NieuwsbriefCommentaar
WHERE (Nieuwsbrief.ID = NieuwsbriefCommentaar.NieuwsbriefID
AND NieuwsbriefCommentaar.Goedgekeurd = 1)) AS AantalCommentaren
FROM Nieuwsbrief
I'm changing now to sql-server-ce (compact edition) which won't allow me to have subqueries like this. Proposed solution : inner join. But as I only need a count of the subtable 'NieuwsbriefCommentaar', I have to use a 'group by' clause on my base table attributes to avoid doubles in the result set.
However the 'Nieuwbrief.Brief' attribute is of datatype 'text'. Group by clauses are not allowed on 'text' datatype in sql-server-ce. 'Text' datatype is deprecated, but sql-server-ce doesn't support 'nvarchar(max)' yet...
Any idea how to solve this? Thx for your help.
I think that the solution could be easier. I don't know exactly how is your metadata but I think that this code could fit your requirements by simply using LEFT JOIN.
SELECT Nieuwsbrief.ID
, Nieuwsbrief.Titel
, Nieuwsbrief.Brief
, Nieuwsbrief.NieuwsbriefTypeCode
, COUNT(NieuwsbriefCommentaar.NieuwsbriefID) AS AantalCommentaren
FROM Nieuwsbrief
LEFT JOIN NieuwsbriefCommentaar ON (Nieuwsbrief.ID = NieuwsbriefCommentaar.NieuwsbriefID)
WHERE NieuwsbriefCommentaar.Goedgekeurd = 1
Edited: 2ndOption
SELECT N.ID, N.Titel, N.Brief, N.NieuwsbriefTypeCode, G.AantalCommentaren FROM Nieuwsbrief as N LEFT JOIN (SELECT NieuwsbriefID, COUNT(*) AS AantalCommentaren FROM NieuwsbriefCommentaar GROUP BY NieuwsbriefID) AS G ON (N.ID = G.NieuwsbriefID)
Please, let me know if this code works in order to find out another workaround..
regards,