Attempting to set a non-NULL- able column's value to NULL - sql

I am getting attempting to set a non-NULL- able column's value to NULL
error when I use FOR XML PATH('')
Code:
select
fdp.POLICYNUMBER,
fdp.INSUREDNAME,
fdp.OWNERNAME,
fdp.AGENCYCODE,
p.WFWORKSTEPNAME,
fdpc.NIGO,
fdpc.NIGOREASON,
d.NIGOREQUIREMENT,
wci.WCSTATUS,
wci.DATECOMPLETED,
fdCI.NEWUNDERWRITINGUSER,
fdr.NBAMOUNT
into
#t
from
PINewBusiness p
join
FDPolicyDetails fdp on SUBSTRING(p.CFREPKEY, 9, LEN(p.CFREPKEY)) = fdp.PARENT_CASEID
and (p.WFWORKSTEPNAME = 'PendingRequirements' or
p.WFWORKSTEPNAME = 'FollowUpRequirements' )
join
FDProcessing fdpc on SUBSTRING(p.CFREPKEY, 9, LEN(p.CFREPKEY)) = fdpc.PARENT_CASEID
join
FDRounting fdr on SUBSTRING(p.CFREPKEY, 9, LEN(p.CFREPKEY)) = fdr.PARENT_CASEID
cross apply
(select NIGOREQUIREMENT + ', '
from FDNIGORequirements nr
where nr.PARENT_CASEID = fdpc.PARENT_CASEID
for xml path('')) D (NIGOREQUIREMENT)
--join FDNIGORequirements nr on SUBSTRING(p.CFREPKEY, 9, LEN(p.CFREPKEY)) = nr.PARENT_CASEID
cross apply
(select NIGOREQUIREMENT + ', '
from FDNIGORequirements nr
where nr.PARENT_CASEID = SUBSTRING(p.CFREPKEY,9,LEN(p.CFREPKEY))
for xml path('')) D (NIGOREQUIREMENT)
join
(select max(CREATEDDATETIME) as CREATEDDATETIME, PARENT_CASEID
from FDWelcomeCall
group by PARENT_CASEID ) wc on fdr.PARENT_CASEID = wc.PARENT_CASEID
join
FDWelcomeCall wci on wci.PARENT_CASEID = wc.PARENT_CASEID
and wci.CREATEDDATETIME = wc.CREATEDDATETIME
join
FDCaseInformation fdCI on SUBSTRING(p.CFREPKEY, 9, LEN(p.CFREPKEY)) = fdCI.PARENT_CASEID
where
p.WFSTEPENTRYTIME >= #sdate
and p.WFSTEPENTRYTIME <= #edate
order by
p.WFFLOWENTRYTIME desc

If you want to keep the rows with NULL values you must replace the nulls in the column that gives you the error, to do so you can use:
SELECT COALESCE([MyColumn],__ReplacementValue__) AS [MyColumn] FROM MyTable
or
SELECT ISNULL([MyColumn],__ReplacementValue__) AS [MyColumn] FROM MyTable
You can use one of them in the inner or outer SELECT.
Otherwise, if the row should not exist if that value is null you must filter it out by adding a WHERE clause:
WHERE [MyColumn] IS NOT NULL

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
...

I am converting Oracle queries to Standard Bigquery, i am gettting error "IN subquery is not supported inside join predicate."

I have converted oracle query into below standard bq but in last statement(IN subquery). I am getting error:
"IN subquery is not supported inside join predicate."
Please advise how to use IN subquery in bq in the below code
#Last part of the code
INNER JOIN (
SELECT
DISTINCT `domain-rr.oracle_DB_DB.he_project_assoc`.PARENT_ISBN
PARENT_ISBN,
SUM (`domain-rr.DB_RPT.PROJECT_GR_QTY`.GR_QTY) GR_QTY
FROM
`domain-rr.oracle_DB_DB.he_project_assoc`
INNER JOIN
`domain-rr.DB_RPT.PROJECT_GR_QTY`
ON
`domain-rr.oracle_DB_DB.he_project_assoc`.child_ISBN = `domain-
rr.DB_RPT.PROJECT_GR_QTY`.BIC_GCISBN
AND `domain-rr.oracle_DB_DB.he_project_assoc`.BREAK_LABEL <>
'Associated ISBNs'
GROUP BY
`domain-rr.oracle_DB_DB.he_project_assoc`.PARENT_ISBN) xx
ON
yy.PARENT_ISBN = xx.PARENT_ISBN
AND yy.CIRCULATION_INT < xx.GR_QTY
AND yy.PARENT_ISBN IN
( SELECT
DISTINCT _BIC_GCISBN
FROM
`domain-rr.DB_RPT.BIC_GM_AGCPOAODS00_BO_VW`
INNER JOIN
`domain-rr.oracle_DB_boadmin.fiscal_bo`
ON
_BIC_ZC2GRIRIN = 'G'
AND _BIC_ZCLOEKZ = ' '
AND SUBSTR (BOUND_DATE, 1, 6) = `domain-
rr.oracle_DB_boadmin.fiscal_bo`.PRIOR_FISC_YEAR_MONTH )
Can you try like this:
Select * from (
#Last part of the code
INNER JOIN (
SELECT
DISTINCT `pearson-rr.oracle_grdw_grdw.he_project_assoc`.PARENT_ISBN
PARENT_ISBN,
SUM (`pearson-rr.GRDW_RPT.PROJECT_GR_QTY`.GR_QTY) GR_QTY
FROM
`pearson-rr.oracle_grdw_grdw.he_project_assoc`
INNER JOIN
`pearson-rr.GRDW_RPT.PROJECT_GR_QTY`
ON
`pearson-rr.oracle_grdw_grdw.he_project_assoc`.child_ISBN = `pearson-
rr.GRDW_RPT.PROJECT_GR_QTY`.BIC_GCISBN
AND `pearson-rr.oracle_grdw_grdw.he_project_assoc`.BREAK_LABEL <>
'Associated ISBNs'
GROUP BY
`pearson-rr.oracle_grdw_grdw.he_project_assoc`.PARENT_ISBN) xx
ON
yy.PARENT_ISBN = xx.PARENT_ISBN
AND yy.CIRCULATION_INT < xx.GR_QTY
) AA
where AA.PARENT_ISBN IN
( SELECT
DISTINCT _BIC_GCISBN
FROM
`pearson-rr.GRDW_RPT.BIC_GM_AGCPOAODS00_BO_VW`
INNER JOIN
`pearson-rr.oracle_grdw_boadmin.fiscal_bo`
ON
_BIC_ZC2GRIRIN = 'G'
AND _BIC_ZCLOEKZ = ' '
AND SUBSTR (BOUND_DATE, 1, 6) = `pearson-
rr.oracle_grdw_boadmin.fiscal_bo`.PRIOR_FISC_YEAR_MONTH )

Data show by list when group by is not include data

I have a sql command like this
select mainPOID.EstAPDate,mainPOID.POID,TTm.ID,TTMAmount=TTMD.InvoiceAmount
From TTBeforeMms TTM
inner join TTBeforeMms_Detail TTMD on TTM.ID = TTMD.ID
inner join (
select distinct main.EstAPDate,main_D.POID
From AP main
left join AP_Detail main_D on main.ID = main_D.ID
where main.Type ='PA' and main.EstAPDate between '2018/6/01' AND '2018/6/15' and left(main_D.InvoiceNo,4) != '1111' ) mainPOID on TTMD.poid =mainPOID.POID and TTM.EstAPdate<=mainPOID.EstAPdate and mainPOID.POID='CM3PU18030009'
order by mainPOID.EstAPDate,mainPOID.POID
sql result will like this
My question is
How can Data show by list when group by is not include data?
For example
ID will show by list When I group by EstAPDate、POID and sum(TTMAmount)
You can store in one temp table or use CTE
CREATE TABLE [dbo].#Columnss(
espapdate date ,
poid varchar(max),
id varchar(max),amount decimal(22,6))
GO
insert into #Columnss values('2018-06-15','cm3','pt20',19988.8900)
insert into #Columnss values('2018-06-15','cm3','pt21',265.8900)
SELECT
REPLACE(ESPAPDATE,'-','/') ESPAPDATE, POID,
STUFF(
(SELECT ' , ' + OD.ID
FROM #COLUMNSS OD
WHERE OD.ESPAPDATE = O.ESPAPDATE
AND OD.POID = O.POID
FOR XML PATH('')), 1, 2, ''
) PRODUCTNAMES,SUM(AMOUNT)AMOUNT
FROM #COLUMNSS O
GROUP BY ESPAPDATE, POID
output
espapdate poid ProductNames amount
2018/06/15 cm3 pt20 , pt21 20254.780000
there are lots of CSV example using FOR XML PATH. For your case here, i am wrapping your existing query in a CTE and then from there generate the CSV string for ID
; with
cte as
(
select mainPOID.EstAPDate, mainPOID.POID, TTm.ID, TTMAmount=TTMD.InvoiceAmount
From TTBeforeMms TTM
inner join TTBeforeMms_Detail TTMD on TTM.ID = TTMD.ID
inner join (
select distinct main.EstAPDate,main_D.POID
From AP main
left join AP_Detail main_D on main.ID = main_D.ID
where main.Type ='PA'
and main.EstAPDate between '2018/6/01' AND '2018/6/15'
and left(main_D.InvoiceNo,4) != '1111'
) mainPOID on TTMD.poid = mainPOID.POID
and TTM.EstAPdate <= mainPOID.EstAPdate
and mainPOID.POID = 'CM3PU18030009'
)
SELECT EstAPDate, POID,
ID = STUFF(c.ID, 1, 1, ''),
TTMAmount = SUM(TTMAmount)
FROM cte
CROSS APPLY
(
SELECT ',' + ID
FROM cte x
WHERE x.EstAPDate = cte.EstAPDate
AND x.POID = cte.POID
FOR XML PATH ('')
) c (ID)
GROUP BY EstAPDate, POID
ORDER BY EstAPDate, POID

Cross Apply remove NULL values

I want to remove the row with NULL values on Crit_Value column. Appreciate your help.
Query:
SELECT DISTINCT GP.PRIORITY_CD, CODE_Val
FROM TCRITERIA_GROUP_PS GP
CROSS APPLY ( SELECT PV.CODE + ','
FROM TCRITERIA_GROUP_PS_VALUE GPV
--JOIN TCRITERIA_GROUP_PS GP ON GP.CRITERIA_GROUP_PS_ID = GPV.CRITERIA_GROUP_PS_ID
JOIN TCRITERIA_PS_VALUE PV ON PV.CRITERIA_PS_VALUE_ID = GPV.CRITERIA_PS_VALUE_ID
JOIN TCRITERIA_PS CP ON PV.CRITERIA_PS_ID = CP.CRITERIA_PS_ID
WHERE
PV.PARTNER_ID = 'JETSTAR'
AND GP.PARTNER_SYS_ID = 'JETSTAR1'
AND GP.ISO_CNTRY_CD = 'AU'
AND GP.CRITERIA_GROUP_PS_ID = GPV.CRITERIA_GROUP_PS_ID
FOR XML PATH('') ) D ( CODE_Val )
RESULTSET of the Query:
PRIORITY_CD CODE_Val
-------------------------
1 NULL
1 AU,AU,AUD,OW,0_1999,
2 NULL
2 AU,AU,AUD,OW,2000_99999,
3 NULL
3 AU,AU,AUD,RT,0_1999,
4 NULL
4 AU,AU,AUD,RT,2000_99999,
5 NULL
5 AU,ALL_EX,AUD,OW,
Try changing the correlation between the main table and the subquery, or add a where clause to filter out the NULLs
SELECT DISTINCT
GP.PRIORITY_CD
, D.CODE_Val
FROM TCRITERIA_GROUP_PS GP
CROSS APPLY (
SELECT
PV.CODE + ','
FROM TCRITERIA_GROUP_PS_VALUE GPV
JOIN TCRITERIA_PS_VALUE PV ON PV.CRITERIA_PS_VALUE_ID = GPV.CRITERIA_PS_VALUE_ID
JOIN TCRITERIA_PS CP ON PV.CRITERIA_PS_ID = CP.CRITERIA_PS_ID
WHERE PV.PARTNER_ID = 'JETSTAR'
AND GP.PARTNER_SYS_ID = 'JETSTAR1'
AND GP.ISO_CNTRY_CD = 'AU'
AND GP.PRIORITY_CD = GPV.CRITERIA_GROUP_PS_ID -- changed
FOR xml PATH ('')
) D (CODE_Val)
-- WHERE D.CODE_Val IS NOT NULL

multiple errors in using with function in select statement

I'm having some problems with my select statement. When I try to execute it, it gives 3 errors
Must specify table to select from
An object or column name is missing or empty for SELECT INFO statements. verify each column
has a name. For other statements, look for empty alias names. Aliases defined...
Column name or number of supplied values does not match table definition.
WITH A AS
(SELECT ROW_NUMBER() OVER (ORDER BY
CASE
WHEN #pOrderBy = 'SortByName' THEN colPortAgentVendorNameVarchar
WHEN #pOrderBy = 'SortByCOuntry' THEN colCountryNameVarchar
WHEN #pOrderBy = 'SortByCity' THEN colCityNameVarchar
END,
colPortAgentVendorNameVarchar
) xRow, A.*
FROM
(
SELECT DISTINCT
V.colPortAgentVendorIDInt,
colPortAgentVendorNameVarchar = RTRIM(LTRIM(V.colPortAgentVendorNameVarchar)),
C.colCountryNameVarchar,
Y.colCityNameVarchar,
V.colContactNoVarchar,
V.colFaxNoVarchar,
V.colEmailToVarchar,
V.colWebsiteVarchar,
BR.colBrandIdInt,
PR.colPriorityTinyint,
colBrandCodeVarchar = RTRIM(LTRIM(BR.colBrandCodeVarchar))
FROM dbo.TblVendorPortAgent V
LEFT JOIN TblCountry C ON C.colCountryIDInt = V.colCountryIDInt
LEFT JOIN TblCity Y ON Y.colCityIDInt = V.colCityIDInt
LEFT JOIN tblBrandAirportPortAgent PR ON PR.colPortAgentVendorIDInt = V.colPortAgentVendorIDInt
AND PR.colIsActiveBit = 1
LEFT JOIN TblBrand BR ON BR.colBrandIdInt = PR.colBrandIdInt
AND BR.colIsActiveBit = 1
WHERE V.colIsActiveBit = 1
AND V.colPortAgentVendorNameVarchar LIKE '%'+ #pPortAgentVendor +'%'
AND (PR.colBrandIdInt = #pBrandID OR #pBrandID = 0)
) A
)
INSERT INTO #tempPortAgent
SELECT A.*, IsWithContract = CASE WHEN colContractIdInt IS NULL THEN CAST(0 AS BIT) ELSE CAST(1 AS BIT) END FROM A LEFT JOIN TblContractPortAgent B ON A.colPortAgentVendorIDInt = B.colPortAgentVendorIDInt
AND B.colIsActiveBit = 1
;WITH QQ AS
(
SELECT ROW_NUMBER() OVER(PARTITION BY Q.colPortAgentVendorIDInt ORDER BY xRow,
ContractStatusOrder,
colDateCreatedDate DESC
)ContractRow,*
FROM
(
SELECT DISTINCT GG.*, B.colContractIdInt, B.colContractStatusVarchar, B.colDateCreatedDate ,
ContractStatusOrder = CASE WHEN B.colContractStatusVarchar = 'Approved' THEN 1 ELSE '2' END
FROM #tempPortAgent GG LEFT JOIN TblContractPortAgent B ON GG.colPortAgentVendorIDInt = B.colPortAgentVendorIDInt
AND B.colIsActiveBit = 1
) Q
)SELECT * INTO #tempPortAgentWithContract
SELECT * FROM #tempPortAgentWithContract
I don't really know where its showing, because the errors are saying that these are inside the select statements inside.
1- Use Select Into instead of Insert into select
SELECT A.*, IsWithContract = CASE WHEN colContractIdInt IS NULL THEN CAST(0 AS BIT) ELSE CAST(1 AS BIT) END
Into #tempPortAgent
FROM A
LEFT JOIN TblContractPortAgent B ON A.colPortAgentVendorIDInt = B.colPortAgentVendorIDInt
AND B.colIsActiveBit = 1
2- SELECT * INTO #tempPortAgentWithContract is incorrect syntax. you must use following format:
SELECT * INTO #tempPortAgentWithContract From QQ