Parsing error when creating view - sql

I have a view which takes multiple rows and Comma Separated Values (CSV) from table columns with data.
It was working well and I got the results that I needed. Now the view has some parsing error like:
Error in WHERE clause near '('. Unable to parse query text.
Can someone help? Here is my code:
SELECT dbo.table1.title,
Stuff((SELECT ', ' + CONVERT(NVARCHAR(4000), dbo.table3.uid) AS [text()]
FROM dbo.table2
INNER JOIN dbo.table3
ON dbo.table3.uid = dbo.table2.FK_Group
WHERE dbo.table3.uid = dbo.table2.FK_Group
AND dbo.table3.company = dbo.main.company
AND dbo.table2.FK_Version = dbo.table1.fk_Version
AND dbo.main_version.uid = dbo.table1.fk_Version
FOR XML PATH('')), 1, 1, '') AS groupName
FROM dbo.main_version
INNER JOIN dbo.[main]
ON dbo.version.fk_main = dbo.[main].uid
INNER JOIN dbo.main_schema
ON dbo.[main].fk_SCHEMA = dbo.main_schema.uid
INNER JOIN dbo.table1
ON dbo.version.uid = dbo.table1.fk_Version
WHERE ( dbo.main_version.active = 1 )

Related

How do I use a CASE statement in a JOIN in SQL Server?

I have a stored procedure that I want to select a column if the applicationTypeId is in a list of IDs. I am trying to use the CASE statement but I don't know what I am doing wrong. I created a table and added the ApplicationTypeIds to it. The table name is #RelationshipsTypeApplicationId
In other words, what I am trying to do is the following:
If the applicationTypeId is in the #RelationshipsTypeApplicationId table
Join and select the Name column from the IGCRelationshipTypes table
Here is my original stored procedure
WITH AllCustomers AS
(
SELECT
app.ApplicationId,
cust.Name,
ApplicationTypes.TypeName AS ApplicationType,
ApplicationSources.ApplicationSourceName AS ApplicationSource,
CreatedDate = app.CreatedDate,
LastUpdateDate = app.StatusChangeDate,
app.StatusId,
InProgress = STUFF((SELECT ';'+#aw.ApplicationWorkflowName
FROM #aw
WHERE #aw.ApplicationId = app.ApplicationId
ORDER BY StepNumber
FOR XML PATH('')), 1, 1, ''),
ActionRequired = (SELECT top 1 1 FROM #aw
WHERE #aw.ApplicationId = app.ApplicationId
AND #aw.WorkflowStatusId = 6),
AccountId = STUFF((SELECT ';' + acct.AccountId
FROM #accounts AS acct
WHERE acct.ApplicationId = app.ApplicationId
ORDER BY acct.ParentAccountId
FOR XML PATH('')), 1, 1, '')
FROM
[dbo].[Applications] app
INNER JOIN
[dbo].[Customers] AS cust ON cust.CustomerId = app.CustomerId
INNER JOIN
[dbo].[ApplicationTypes] ON ApplicationTypes.ApplicationTypeId = app.ApplicationTypeId
INNER JOIN
[dbo].[ApplicationSources] ON ApplicationSources.ApplicationSourceId = app.ApplicationSourceId
WHERE
app.StatusId <> '4020-8901-64FFE33F06B1'
AND (#applicationTypeId IS NULL OR app.ApplicationTypeId = #applicationTypeId)
And here is what I updated:
WITH AllCustomers AS
(
SELECT
app.ApplicationId,
cust.Name,
ApplicationTypes.TypeName AS ApplicationType,
ApplicationSources.ApplicationSourceName AS ApplicationSource,
CreatedDate = app.CreatedDate,
LastUpdateDate = app.StatusChangeDate,
app.StatusId,
InProgress = STUFF((SELECT ';' + #aw.ApplicationWorkflowName
FROM #aw
WHERE #aw.ApplicationId = app.ApplicationId
ORDER BY StepNumber
FOR XML PATH('')), 1, 1, ''),
ActionRequired = (SELECT top 1 1 FROM #aw
WHERE #aw.ApplicationId = app.ApplicationId
AND #aw.WorkflowStatusId = 6),
AccountId = STUFF((SELECT ';' + acct.AccountId
FROM #accounts as acct
WHERE acct.ApplicationId = app.ApplicationId
ORDER BY acct.ParentAccountId
FOR XML PATH('')), 1, 1, ''),
CASE
WHEN app.ApplicationTypeId IN (SELECT * FROM #RelationshipsTypeApplicationId)
THEN relationshipType.Name
END
FROM
[dbo].[Applications] app
INNER JOIN
[dbo].[Customers] AS cust ON cust.CustomerId = app.CustomerId
INNER JOIN
[dbo].[ApplicationTypes] ON ApplicationTypes.ApplicationTypeId = app.ApplicationTypeId
INNER JOIN
[dbo].[ApplicationSources] ON ApplicationSources.ApplicationSourceId = app.ApplicationSourceId
INNER JOIN
[dbo].[IGCRelationshipTypes] AS relationshipType
ON CASE
WHEN app.ApplicationTypeId IN (SELECT * FROM #RelationshipsTypeApplicationId)
THEN (relationshipType.Name = #relationshipType)
END
WHERE
app.StatusId <> '4020-8901-64FFE33F06B1'
AND (#applicationTypeId IS NULL OR app.ApplicationTypeId = #applicationTypeId)
Here is a screenshot of the syntax error:
Can someone shed some light on what I am missing here?
CASE in T-SQL is an expression that returns a single scalar value, it is not for control of flow. See Dirty secrets of the CASE expression. You'll need something like this, but I don't have the energy to try to determine why you have a table named #RelationshipsTypeApplicationId with a single column (because you really shouldn't say IN (SELECT *)) or if you want to do something different when the match does not exist.
...
ON relationshipType.Name = CASE
WHEN app.ApplicationTypeId IN
(SELECT * FROM #RelationshipsTypeApplicationId)
THEN #relationshipType END
...

Azure Cognitive Search: How to get collection of strings from a view

I have an index definition on the Azure Cognitive Search and inside this index definition, there is a field called CustomerNames which of type collection (Collection(Edm.String)). Basically, this means my collection result will look like this: CustomerNames: ["Homer Simpson", "Henry Griffin", "Jane Doe"]
Here is the snapshot of the index definition:
Now I have a view that will act as a data source in this cognitive search and this view is:
CREATE VIEW [dbo].[vCog_CustomerActivityAttachmentSearchDocuments]
AS
SELECT
caa.Id,
caa.CustomerActivityId,
caa.AmsAttachmentId,
caa.OriginalFileName,
caa.[FileName],
caa.FileExtension,
caa.ContentType,
caa.[Description],
caa.DocumentTypeId,
caa.AdditionalInfo,
caa.Comments,
ca.CustomerId,
GuidCustomerId = ca.CustomerId,
CustomerNames =
(
SELECT
STRING_AGG(CONVERT(nvarchar(max),cp.FirstName + ' ' + cp.LastName), ', ')
FROM dbo.CustomerPersons AS cp with (nolock)
WHERE cp.CustomerId = c.Id AND cp.LegalEntityName IS NULL
),
CustomerPersons =
(
Select
cp.Id
, cp.CustomerId
, cp.NamePrefix
, cp.FirstName
, cp.MiddleName
, cp.LastName
, cp.DateOfBirth
, cp.HomePhone
, cp.WorkPhone
, cp.CellPhone
, cp.FaxPhone
, cp.Email
, cp.Email2
, cp.LegalEntityName
from
CustomerPersons cp with (nolock)
where
cp.CustomerId = c.Id FOR JSON AUTO
),
c.FirmName,
ca.PolicyId,
PolicyNumber = p.TrimmedPolicyNumber,
caa.CreatedAtUtc,
caa.[RowVersion]
FROM dbo.CustomerActivityAttachments caa with (nolock)
JOIN dbo.CustomerActivities ca with (nolock) on ca.Id = caa.CustomerActivityId
JOIN dbo.Customers c with (nolock) on c.Id = ca.CustomerId
LEFT JOIN dbo.Policies p with (nolock) on p.Id = ca.PolicyId
where IsNull(caa.UpdatedAtUtc, caa.CreatedAtUtc) > GetDate() - 1200
GO
So when I run the indexer on the cognitive search, it is unable to recognize the CustomerNames and throwing the following error:
The data field 'CustomerNames' in the document with key 'XXXXXXXX' has an invalid value of type 'Edm.String' (String maps to Edm.String). The expected type was 'Collection(Edm.String)'.
So my question is how do I change my query in a way that I am getting a JSON array of strings and making it recognizable by the search function?
What I have tried so far: I have tried using this query inside the customerNames:
SELECT
JSON_QUERY('[' + STUFF(( SELECT ',' + '"' + STRING_AGG(CONVERT(nvarchar(max),cp.FirstName + ' ' + cp.LastName), ', ') + '"'
FROM dbo.CustomerPersons AS cp with (nolock)
WHERE cp.CustomerId = c.Id AND cp.LegalEntityName IS NULL
FOR XML PATH('')),1,1,'') + ']') as [CustomerNames]
FOR JSON PATH , WITHOUT_ARRAY_WRAPPER
But this is not solving the problem. Any ideas will be greatly appreciated. Thanks in advance.
you can use Field mapping function - jsonArrayToStringCollection to convert the json array to Index collection
So let your query generate a column with name CustomerNamesJArray and map it to CustomerNames and have a jsonArrayToStringCollection mapping function.
https://learn.microsoft.com/en-us/azure/search/search-indexer-field-mappings#field-mapping-functions

Create View with 'STUFF' function - conversion failed nvarchar to data type int

I am confused I created a view that uses the STUFF function on an int. It was working however I had to drop my table and reload it and now my view is not working. I receive the following error Conversion failed when converting the nvarchar value ' 5, 4' to data type int.. I am loading the table from the same insert script that I used last time with the addition of one field which shouldn't have an affect. My create view script is as follows:
CREATE VIEW [AQB_OB].[GISREQUESTEDBURNS]
AS
with conditions as
(SELECT DISTINCT BD.[RequestedBurnsID]
,[ConditionsReasonsID] = STUFF((SELECT ', ' + CONVERT(VARCHAR(20),[ConditionsReasonsID]) FROM [AQB_OB].[BurnDecisions] WHERE [RequestedBurnsID]= BD.[RequestedBurnsID] ORDER BY [RequestedBurnsID] ASC
FOR XML PATH ('')) , 1 , 1, '') FROM
[AQB_OB].[BurnDecisions] BD)
SELECT RB.[RequestedBurnsID] AS REQUESTEDBURNID
,BUY.[BurnYear] AS BURNYEAR
,CY.[CurrentYear] AS CURRENTYEAR
,RB.[BurnSitesID] AS BURNSITESID
,[BurnerID] AS BURNERID
,[Contact] AS CONTACT
,[Latitude] AS LATITUDE
,[Longitude] AS LONGITUDE
,[BurnStartDate] AS BURNSTARTDATE
,[BurnEndDate] AS BURNENDDATE
,RB.[NumberPiles] AS NUMBERPILES
,[BurnDecision] AS BURNDECISION
,RB.[Comment] AS COMMENT
,CC.ConditionsReasonsID AS CONDITIONS
FROM [AQB_MON].[AQB_OB].[RequestedBurns] RB
inner join AQB_MON.[AQB_OB].[BurnSites] BS on RB.BurnSitesID = BS.BurnSitesID
inner join AQB_MON.[AQB_OB].[Contacts] CT on RB.ContactsID = CT.ContactsID
inner join AQB_MON.[AQB_OB].[BurnProject] BP on BP.BurnProjectID = BS.BurnProjectID
inner join AQB_MON.[AQB_OB].[BurnYears] BUY on BUY.BurnYearID = BP.BurnYearID
inner join AQB_MON.[AQB_OB].[CurrentYear] CY on CY.CurrentYearID = BUY.CurrentYearID
full outer join conditions CC on CC.RequestedBurnsID = RB.RequestedBurnsID
INNER JOIN [AQB_OB].[ConditionsReasons] CR ON CR.ConditionsReasonsID = CC.ConditionsReasonsID
GO

Complex Query Incorrect Syntax Error

I have tried to search for a solution to this but I have not been able to find one that fits this situation.
First I must say that my SQL is a lot rusty. The following query is the most complex one I have ever done to date.
Here is the query:
Declare #root varchar(Max)
set #root = ''
Select
ib.irrnum, ib.status, pu.probtype,
ib.submitby, ta.[Task Action], ib.area, co.cost,
rc.rootcause, ib.jobnum
From
tbl_irrbase ib
Left Join
tbl_cost co On ib.irrnum = co.irrnum
Left join
(Select Distinct probtype, irrnum
From tbl_probtype) pu On ib.irrnum = pu.irrnum
Left Join
(Select Distinct rootcause, irrnum
From tbl_rtcause) rc On ib.irrnum = rc.irrnum
Left Join
(Select TOP 1
(owner + Space(1) + Convert(varchar(10), senddate, 101) + Space(1) + taskitem) As 'Task Action',
irrnum
From
(select * From tbl_taskaction) ta
Order by
senddate Desc, sendtime Desc) ta On ib.irrnum = ta.irrnum
left Join
(Select [#root] = #root + rs.rootsource + Space(3), irrnum
From tbl_rtsource rs
Where rs.entrydate Between '10/04/2016' And '10/06/2016'
Select #root As 'Root Source') sr On ib.irrnum = sr.irrnum
Where
ib.submitedate between '09/28/2016' And '10/05/2016'
My problem is with the last Left Join line. If I take the entire Select statement out and run it in SSMS it runs fine, no errors. But when I try and run it in this query I get an error, red squiggly line under 'Select #root As' telling me the following:
Incorrect Syntax near 'Select'.
Expecting ')', EXCEPT, or UNION
I do not know how to fix this. If I remove this last 'Left Join' line the query runs fine.
Any ideas?
Instead of the last LEFT JOIN, try something like this:
CROSS APPLY (
SELECT (
SELECT rs.rootsource + Space(3)
From tbl_rtsource rs
Where rs.entrydate Between '10/04/2016' And '10/06/2016'
AND rs.irrnum=ib.irrnum
FOR XML PATH('')
) AS rootsource
) sr
Then include sr.rootsource in the columns of the first SELECT.

SQL server Stuff on multiple columns

I want to concatenate the value of multiple columns for the same ID.
I managed to concatenate for the first column, but when trying the same syntax for the second I'm having an error "The multi-part identifier EnqAct.[ActionID] could not be bound."
Example_Data_Result
Here I managed to group several MachineName together, as seen in "Column1" but I can't manage to group both the MachineName and Description in their own column
My working Query :
SELECT Enq.[EnquiryID],
Enq.[CustomerName],
DetPrio.[Description],
Stuff((SELECT ', ' + Mach.[MachineName]
FROM [dbo].[Machine] Mach
INNER JOIN [dbo].[MachineEnquiry] MachEnq
ON Mach.[MachineID] = MachEnq.[MachineID]
WHERE Enq.[EnquiryID] = MachEnq.[EnquiryID]
FOR XML PATH('')), 1, 2, ''),
DetAct.[Description]
FROM [dbo].[Enquiry] Enq
INNER JOIN [dbo].[EnquiryAction] EnqAct
ON EnqAct.[EnquiryID] = Enq.[EnquiryID]
INNER JOIN [dbo].[DetailsAction] DetAct
ON DetAct.[ActionID] = EnqAct.[ActionID]
INNER JOIN [dbo].[DetailsPriority] DetPrio
ON DetPrio.[PriorityID] = Enq.[Priority]
GROUP BY Enq.[EnquiryID],
Enq.[CustomerName],
DetPrio.[Description],
DetAct.[Description]
My non working Query :
SELECT Enq.[EnquiryID],
Enq.[CustomerName],
DetPrio.[Description],
Stuff((SELECT ', ' + Mach.[MachineName]
FROM [dbo].[Machine] Mach
INNER JOIN [dbo].[MachineEnquiry] MachEnq
ON Mach.[MachineID] = MachEnq.[MachineID]
WHERE Enq.[EnquiryID] = MachEnq.[EnquiryID]
FOR XML PATH('')), 1, 2, ''),
Stuff((SELECT ', ' + DetAct.[Description]
FROM [dbo].[DetailsAction] DetAct
INNER JOIN [dbo].[EnquiryAction] EnqAct
ON EnqAct.[ActionID] = DetAtc.[ActionID]
WHERE Enq.[EnquiryID] = EnqAct.[EnquiryID]
FOR XML PATH('')), 1, 2, '')
FROM [dbo].[Enquiry] Enq
INNER JOIN [dbo].[DetailsPriority] DetPrio
ON DetPrio.[PriorityID] = Enq.[Priority]
GROUP BY Enq.[EnquiryID],
Enq.[CustomerName],
DetPrio.[Description]
Both work the same way, I have a table Enquiry which will have an EnquiryID.
then in my table EnquiryAction or MachineEnquiry I will have entitys with an EnquiryID and an Action/Machine ID
Then in my DetailsAction/Machine Table I will have the Action/Machine ID, and the string I want to get and concatenate.
Why am I having an error and is it possible to achieve what I'm trying to do ?