How I can transform a stored procedure to a view? - sql-server

I have this stored procedure which pulls data from 4 tables and ranks them by 4 columns, but I need a view with the same result (of course without parameter). Is this possible? I know that I can not use a temp table in view, any solution?!
ALTER PROC pr_GetChildrenByPersonID
#pePersonIDs varchar(8000)
AS
SELECT
*,
RANK() OVER (PARTITION BY pbsPersonID ORDER BY psbPersonSiblingID ASC) AS CustomRank
INTO
#TempPersonSibling
FROM
PersonSibling
WHERE
pbsSiblingTypeID = 2
AND pbsPersonID IN (SELECT item
FROM dbo.fn_ParseStrListIdentity(#pePersonIDs, ','))
SELECT
pePersonID,
ISNULL((SELECT pbsName
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 1), '') AS ChildrenName1,
ISNULL((SELECT pbsAge
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 1), '') AS ChildrenAge1,
ISNULL((SELECT dbo.fn_GetCountry(pbsPlaceOfBirth)
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 1), '') AS ChildrenCountryOfBirth1,
ISNULL((SELECT dbo.fn_GetCountry(pbsPresentStay)
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 1), '') AS ChildrenCountryOfResidence1,
ISNULL((SELECT pbsName
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 2), '') AS ChildrenName2,
ISNULL((SELECT pbsAge
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 2), '') AS ChildrenAge2,
ISNULL((SELECT dbo.fn_GetCountry(pbsPlaceOfBirth)
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 2), '') AS ChildrenCountryOfBirth2,
ISNULL((SELECT dbo.fn_GetCountry(pbsPresentStay)
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 2), '') AS ChildrenCountryOfResidence2,
ISNULL((SELECT pbsName
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 3), '') AS ChildrenName3,
ISNULL((SELECT pbsAge
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 3), '') AS ChildrenAge3,
ISNULL((SELECT dbo.fn_GetCountry(pbsPlaceOfBirth)
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 3), '') AS ChildrenCountryOfBirth3,
ISNULL((SELECT dbo.fn_GetCountry(pbsPresentStay)
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 3), '') AS ChildrenCountryOfResidence3,
ISNULL((SELECT pbsName
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 4), '') AS ChildrenName4,
ISNULL((SELECT pbsAge
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 4), '') AS ChildrenAge4,
ISNULL((SELECT dbo.fn_GetCountry(pbsPlaceOfBirth)
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 4), '') AS ChildrenCountryOfBirth4,
ISNULL((SELECT dbo.fn_GetCountry(pbsPresentStay)
FROM #TempPersonSibling
WHERE pbsSiblingTypeID = 2
AND pbsPersonID = pepersonID
AND CustomRank = 4), '') AS ChildrenCountryOfResidence4
FROM
Person
WHERE
pePersonID IN (SELECT item
FROM dbo.fn_ParseStrListIdentity(#pePersonIDs, ','))

Use a Common Table Expression (CTE) instead of a temporary table, and use the CTE where you are using the temporary table now.
Like so:
WITH
TempPersonSibling AS (
-- the select statement that creates the temp table here
-- without the INTO clause
)
SELECT
pePersonID,
ISNULL((SELECT pbsName FROM TempPersonSibling WHERE pbsSiblingTypeID = 2 AND pbsPersonID = pepersonID AND CustomRank = 1),'') AS ChildrenName1,
-- ..., rest of the query is similar
FROM
Person
WHERE
-- ...
This way you can create a single query and package that in your view.

Related

convert SQL server query to snowflake , i need help in calling local variable using javascript

# sql server query:#
CREATE FUNCTION [dbo].[fnCurrencyExchange]
(#ExchngType NVARCHAR(30),
#InCurrMode NVARCHAR(10),
#OutCurMode NVARCHAR(10),
#InDate DATE)
RETURNS DECIMAL(17, 6)
BEGIN
DECLARE #lExchangeRate DECIMAL(17, 7);
DECLARE #2ExchangeRate DECIMAL(17, 7);
DECLARE #3ExchangeRate DECIMAL(17, 7);
DECLARE #4ExchangeRate DECIMAL(17, 7);
DECLARE #currdate NVARCHAR(30);
IF ISNULL(#ExchngType,'') = '' -- Default use Balance Sheet Exchnage rate
SET #ExchngType = 'Income Statement';
IF ( #InCurrMode = #OutCurMode AND #InCurrMode IS NOT NULL AND #OutCurMode IS NOT NULL )
RETURN 1;
IF #InDate = ''
SET #currdate = getDate();
Else
SET #currdate = #InDate;
SELECT TOP 1 #lExchangeRate = ExchangeRate
FROM (SELECT a.ExchangeRate ExchangeRate
, Row_number() OVER (ORDER BY a.ValidFrom DESC) Id
FROM [STG].[stgFXRateOut] a
WHERE a.FromCurrency = #InCurrMode
AND a.ToCurrency = #OutCurMode
AND a.ValidFrom <= #currdate
AND a.ExchangeRatetype = #ExchngType
) f
WHERE id = 1;
IF #lExchangeRate IS NOT NULL
RETURN #lExchangeRate;
IF #lExchangeRate IS NULL
BEGIN
SELECT TOP 1 #lExchangeRate = ExchangeRate
FROM (SELECT a.ExchangeRate ExchangeRate
, Row_number() OVER (ORDER BY a.ValidFrom DESC) Id
FROM [STG].[stgFXRateOut] a
WHERE a.FromCurrency = #OutCurMode
AND a.ToCurrency = #InCurrMode
AND a.ValidFrom <= #currdate
AND a.ExchangeRatetype = #ExchngType
) f
WHERE id = 1;
END
IF #lExchangeRate IS NOT NULL
RETURN ( 1 / #lExchangeRate );
IF #lExchangeRate IS NULL
BEGIN
SELECT TOP 1 #lExchangeRate = ExchangeRate
FROM (SELECT a.ExchangeRate ExchangeRate
, Row_number() OVER (ORDER BY a.ValidFrom DESC) Id
FROM [STG].[stgFXRateOut] a
WHERE a.FromCurrency = #InCurrMode
AND a.ToCurrency = 'USD'
AND a.ValidFrom <= #currdate
AND a.ExchangeRatetype = #ExchngType
) f
WHERE id = 1;
IF #lExchangeRate IS NULL
SELECT TOP 1 #lExchangeRate = 1 / (CASE WHEN exchangerate = 0 THEN 1 ELSE exchangerate END)
FROM (SELECT a.ExchangeRate ExchangeRate
, Row_number() OVER (ORDER BY a.ValidFrom DESC) Id
FROM [STG].[stgFXRateOut] a
WHERE a.FromCurrency = 'USD'
AND a.ToCurrency = #InCurrMode
AND a.ValidFrom <= #currdate
AND a.ExchangeRatetype = #ExchngType
) f
WHERE id = 1;
SELECT TOP 1 #2ExchangeRate = exchangerate
FROM (SELECT a.ExchangeRate ExchangeRate,
Row_number() OVER (ORDER BY a.ValidFrom DESC) Id
FROM [STG].[stgFXRateOut] a
WHERE a.FromCurrency = #OutCurMode
AND a.ToCurrency = 'USD'
AND a.ValidFrom <= #currdate
AND a.ExchangeRatetype = #ExchngType
) f
WHERE id = 1;
IF #2ExchangeRate IS NULL
SELECT TOP 1 #2ExchangeRate = 1 / (CASE WHEN exchangerate = 0 THEN 1 ELSE exchangerate END)
FROM (SELECT a.ExchangeRate ExchangeRate,
Row_number() OVER (ORDER BY a.ValidFrom DESC) Id
FROM [STG].[stgFXRateOut] a
WHERE a.FromCurrency = 'USD'
AND a.ToCurrency = #OutCurMode
AND a.ValidFrom <= #currdate
AND a.ExchangeRatetype = #ExchngType
) f
WHERE id = 1;
SELECT #3ExchangeRate = ( #lExchangeRate / #2ExchangeRate );
END
RETURN Isnull(#3ExchangeRate, 0);
END
convert this into snowflake , need help on this on?
i tried but i was unsuccessful
CREATE OR REPLACE FUNCTION "fn_FncurrencyExchange"("ExchngType" NVARCHAR(30),"InCurrMode" NVARCHAR(10),"OutCurMode" NVARCHAR(10),"InDate" DATE)
RETURNS NUMBER(17,6)
LANGUAGE JAVASCRIPT
COMMENT='Create Date: 2022-11-25 Author: Performalytic Team '
AS '
var lExchangeRate =p1;
var 2ExchangeRate =p2;
var 3ExchangeRate =p3;
var 4ExchangeRate =p4;
var currdate =p5;
IF (ISNULL(ExchngType,'') = '' )
{ ExchngType = ''Income Statement'';
}
IF ( InCurrMode = OutCurMode AND InCurrMode IS NOT NULL AND OutCurMode IS NOT NULL )
RETURN 1;
IF InDate = ''
{ p5 = CURRENT_DATE();
}
Else
{ p5 = InDate;
}
SELECT p1 = ExchangeRate
FROM (
SELECT a."ExchangeRate" ExchangeRate
, Row_number() OVER (ORDER BY a."ValidFrom" DESC) Id
FROM DBO."DimFXRateOut" a
WHERE a."FromCurrency" = InCurrMode
AND a."ToCurrency" = OutCurMode
AND a."ValidFrom" <= p5
AND a."ExchangeRatetype" = ExchngType
) f
WHERE id = 1 LIMIT 1;
IF p1 IS NOT NULL
RETURN p1;
IF p1 IS NULL
BEGIN
SELECT p1 = ExchangeRate
FROM (SELECT a."ExchangeRate" ExchangeRate
, Row_number() OVER (ORDER BY a."ValidFrom" DESC) Id
FROM DBO."DimFXRateOut" a
WHERE a."FromCurrency" = OutCurMode
AND a."ToCurrency" = InCurrMode
AND a."ValidFrom" <= p5
AND a."ExchangeRatetype" = ExchngType
) f
WHERE id = 1 LIMIT 1;
END
IF p1 IS NOT NULL
RETURN ( 1 / p1 );
IF p1 IS NULL
BEGIN
SELECT p1 = ExchangeRate
FROM (SELECT a."ExchangeRate" ExchangeRate
, Row_number() OVER (ORDER BY a."ValidFrom" DESC) Id
FROM DBO."DimFXRateOut" a
WHERE a."FromCurrency" = InCurrMode
AND a."ToCurrency" = ''USD''
AND a."ValidFrom" <= p5
AND a."ExchangeRatetype" = ExchngType
) f
WHERE id = 1 LIMIT 1;
IF p1 IS NULL
SELECT p1 = 1 / (CASE WHEN exchangerate = 0 THEN 1 ELSE exchangerate END)
FROM (SELECT a."ExchangeRate" ExchangeRate
, Row_number() OVER (ORDER BY a."ValidFrom" DESC) Id
FROM DBO."DimFXRateOut" a
WHERE a."FromCurrency" = ''USD''
AND a."ToCurrency" = InCurrMode
AND a."ValidFrom" <= p5
AND a."ExchangeRatetype" = ExchngType
) f
WHERE id = 1 LIMIT 1;
SELECT p2 = exchangerate
FROM (SELECT a."ExchangeRate" ExchangeRate,
Row_number() OVER (ORDER BY a."ValidFrom" DESC) Id
FROM DBO."DimFXRateOut" a
WHERE a."FromCurrency" = OutCurMode
AND a."ToCurrency" = ''USD''
AND a."ValidFrom" <= p5
AND a."ExchangeRatetype" = ExchngType
) f
WHERE id = 1 LIMIT 1;
END
IF p2 IS NULL
BEGIN
SELECT p2 = 1 / (CASE WHEN exchangerate = 0 THEN 1 ELSE exchangerate END)
FROM (SELECT a."ExchangeRate" ExchangeRate,
Row_number() OVER (ORDER BY a."ValidFrom" DESC) Id
FROM DBO."DimFXRateOut" a
WHERE a."FromCurrency" = ''USD''
AND a."ToCurrency" = OutCurMode
AND a."ValidFrom" <= p5
AND a."ExchangeRatetype" = ExchngType
) f
WHERE id = 1 LIMIT 1;
SELECT p3 = ( p1 / p2 );
END
RETURN ISNULL(p3, 0);
END
;`;
You set the language to JavaScript, you started with JS commands but you try to run SQLs directly. It is also defined as UDF, in this case you can't call SQLs from JavaScript.
Do you need to create a UDF? Then check this one: https://docs.snowflake.com/en/developer-guide/udf/sql/udf-sql.html
If you want conditionals etc, and run SQL directly, consider SQL scripting (but it will be a stored procedure): https://docs.snowflake.com/en/developer-guide/snowflake-scripting/index.html
You may also want to check writing Stored Procedures in JavaScript: https://docs.snowflake.com/en/sql-reference/stored-procedures-javascript.html

How to create view from the given set of code

I have never come across such a large amount of code and I want to make a View with exact same output that my SQL query is generating. The code is exceeding the limit hence I have reduced the code though the code is incomplete but I have tried making view by create view view name but I am unable to make.
I have tried create view view_name as (sql query) but its showing error:
incorrect syntax 'declare'
But when run alone this whole SQL query we are getting result. Is declare part is the problem?
DECLARE #ClientCode VARCHAR(20);
SELECT #ClientCode = FlagValue
FROM ApplicationConfiguration
WHERE FlagName = 'ClientCode';
DECLARE #NoOfColorsInDashboardGraphs VARCHAR(10);
SELECT #NoOfColorsInDashboardGraphs = FlagValue
FROM ApplicationConfiguration
WHERE FlagName = 'NoOfColorsInDashboardGraphs';
DECLARE #TerminologyToNonCompliedCompletedTasks VARCHAR(50);
SELECT #TerminologyToNonCompliedCompletedTasks = FlagValue
FROM ApplicationConfiguration
WHERE FlagName = 'TerminologyToNonCompliedCompletedTasks';
DECLARE #TerminologyToNonCompliedNonCompletedTasks VARCHAR(50);
SELECT #TerminologyToNonCompliedNonCompletedTasks = FlagValue
FROM ApplicationConfiguration
WHERE FlagName = 'TerminologyToNonCompliedNonCompletedTasks';
DECLARE #DeviationFunctionality VARCHAR(50);
SELECT #DeviationFunctionality = FlagValue
FROM ApplicationConfiguration
WHERE FlagName = 'DeviationFunctionality';
DECLARE #ShowPerformedOnDate VARCHAR(10);
SELECT #ShowPerformedOnDate = FlagValue
FROM ApplicationConfiguration
WHERE FlagName = 'ShowPerformedOnDate';
DECLARE #TerminologyToNonCompliedCompletedTasksPerformedOnDtAfterDueDt VARCHAR(50);
SELECT #TerminologyToNonCompliedCompletedTasksPerformedOnDtAfterDueDt = FlagValue
FROM ApplicationConfiguration
WHERE FlagName = 'TerminologyToNonCompliedCompletedTasksPerformedOnDtAfterDueDt';
DECLARE #TerminologyToCompliedTasks VARCHAR(50);
SELECT #TerminologyToCompliedTasks = FlagValue
FROM ApplicationConfiguration
WHERE FlagName = 'TerminologyToCompliedTasks';
DECLARE #TerminologyToPosingRiskTasks VARCHAR(50);
SELECT #TerminologyToPosingRiskTasks = FlagValue
FROM ApplicationConfiguration
WHERE FlagName = 'TerminologyToPosingRiskTasks';
SELECT TL.OID,
E.EntityOID,
U.UnitOID,
D.DeptOID,
E.EntityName,
U.UnitName,
D.DeptName,
(CASE
WHEN ISNULL(LTRIM(RTRIM(U.ShortDesc)), '') = ''
THEN CONVERT(VARCHAR(50), UT.UnitTaskOID)
ELSE U.ShortDesc + '-' + CONVERT(VARCHAR(50), UT.UnitTaskOID)
END) AS 'UnitTaskWithDesc',
UT.[UnitTaskOID],
UT.[TaskOID],
T.LegislationOID,
T.CentralTaskOID,
L.LegislationCategoryOID,
C.LegislationCategory,
ISNULL(
(
SELECT C.CompanyCategory
FROM CompanyCategory C
WHERE C.CompanyCategoryOID = T.CompanyCategoryOID
), '-') CompanyCategory,
L.CentralState,
L.LegislationName,
T.Section_Rule_Regulation_Notification,
S.STATE_OID,
S.STATE_NAME,
T.[Title],
T.[PriorityOID],
P.Priority,
T.[FrequencyOID],
F.Frequency,
T.[Devices],
T.[Section_Rule_Regulation_Notification],
T.[Requirement_Apply],
T.[Task],
T.[Regulating_Authority],
T.[Consequences],
T.[Department],
TL.[Status] AS TaskStatus,
UT.PerformerUserOID,
D.DeptHeadOID,
ISNULL((UDFH.FIRST_NAME + ' ' + UDFH.LAST_NAME), '-') AS 'DeptHead',
UT.DeptSupervisorOID,
ISNULL((UDSup.FIRST_NAME + ' ' + UDSup.LAST_NAME), '-') AS 'Supervisor',
TL.PerformerUserOID AS 'PerformerUserOID_log',
ISNULL((UDPer.FIRST_NAME + ' ' + UDPer.LAST_NAME), '-') AS 'Performer',
ISNULL((UDComp.FIRST_NAME + ' ' + UDComp.LAST_NAME), '-') AS 'TaskCompletedBy',
dbo.FormatDate(#ClientCode, TL.ApproverDt) AS 'ApproverDt',
dbo.FormatDate(#ClientCode, TL.ReviewerDt) AS 'ReviewerDt',
dbo.FormatDate(#ClientCode, TL.SupervisorDt) AS 'SupervisorDt',
dbo.FormatDate(#ClientCode, TL.PerformerDt) AS 'PerformerDt',
CASE
WHEN #DeviationFunctionality = 'Yes'
THEN ISNULL(TL.Deviation, '-')
ELSE ''
END AS 'Deviation',
dbo.FormatDate(#ClientCode, TL.PerformedOnDt) AS 'PerformedOnDt',
dbo.FormatDate(#ClientCode, TL.CompletedDt) AS 'CompletedDt',
ISNULL(TL.Comments, '-') AS 'Comments',
ISNULL(TL.ActivationComment, '-') AS ActivationComment,
ISNULL(TL.ReasonForNonComp, '-') AS 'ReasonForNonComp',
ISNULL(TL.ActionTaken, '-') AS 'ActionTaken',
dbo.GetCompletionDate(#ClientCode, TL.CompletedDt, #ShowPerformedOnDate, #NoOfColorsInDashboardGraphs, TL.PerformedOnDt) AS 'Completed On',
dbo.GetCompletionComment(TL.ActivationComment, TL.Comments, TL.ReviewerComment, TL.CompletedDt, TL.ReviewerCommentDate, TL.PeriodFromDate, TL.PeriodToDate) AS 'CompletionComments',
'' AS UnitDeviceOID,
'' AS TaskDeviceOID,
'' AS 'lblUnitDeviceOIDDesc',
dbo.GetComplianceStatus(TL.[Status], CONVERT(DATETIME, CONVERT(VARCHAR(50), TL.ApproverDt, 112)), CONVERT(DATETIME, CONVERT(VARCHAR(50), TL.CompletedDt, 112)), #NoOfColorsInDashboardGraphs, #TerminologyToNonCompliedCompletedTasks, #TerminologyToNonCompliedNonCompletedTasks, CONVERT(DATETIME, CONVERT(VARCHAR(50), TL.PerformedOnDt, 112)), #ShowPerformedOnDate, #TerminologyToNonCompliedCompletedTasksPerformedOnDtAfterDueDt, #TerminologyToCompliedTasks, #TerminologyToPosingRiskTasks) AS 'ComplianceStatus',
ISNULL(TblLOGTMakerChecker.ConditionalOID, 0) AS MKOID,
ISNULL(TCSV.TaskComplianceStatusValue, '-') AS TaskComplianceStatusValue,
ISNULL(TL.TaskComplianceStatusValueOID, 0) AS TaskComplianceStatusValueOID,
#NoOfColorsInDashboardGraphs AS 'NoOfColorsOnReport',
#TerminologyToNonCompliedCompletedTasks AS 'TerminologyToNonCompliedCompletedTask',
#TerminologyToNonCompliedNonCompletedTasks AS 'TerminologyToNonCompliedNonCompletedTask',
#ShowPerformedOnDate AS 'ShowPerformedOnDate',
#TerminologyToNonCompliedCompletedTasksPerformedOnDtAfterDueDt AS 'TerminologyToNonCompliedCompletedTasksPerformedOnDtAfterDueDt',
#TerminologyToCompliedTasks AS 'TerminologyToCompliedTasks',
(CASE
WHEN(
(
SELECT COUNT(*)
FROM UnitTaskDocs
WHERE UnitTaskOID = UT.UnitTaskOID
AND DueDateId = TL.OID
) > 0)
THEN 'Yes'
ELSE 'No'
END) AS 'DocumentUploaded',
dbo.FormatDate
(#ClientCode,
(
SELECT TOP 1 UPLOADED_DATE
FROM UnitTaskDocs
WHERE UnitTaskOID = UT.UnitTaskOID
AND DueDateId = TL.OID
ORDER BY 1 DESC
)
) AS 'DocUploadedDate',
'No' AS 'DocumentUploadLater',
TL.FeesPaid,
TL.PenaltyPaid,
TL.SecondSupervisorComment,
TL.SecondSupervisorCommentDate,
TL.ThirdSupervisorComment,
TL.ThirdSupervisorCommentDate,
'' AS TaskType,
'-' AS Region,
'-' AS SubRegion
FROM UnitTask UT
INNER JOIN Task T ON T.Task_OID = UT.TaskOID
INNER JOIN LegislationNames L ON L.LegislationOID = T.LegislationOID
INNER JOIN LegislationCategories C ON C.LegislationCategoryOID = L.LegislationCategoryOID
INNER JOIN [STATE] S ON S.STATE_OID = L.StateOID
INNER JOIN Dept D ON D.DeptOID = UT.PerformerDeptOID
INNER JOIN Units U ON U.UnitOID = UT.UnitOID
INNER JOIN Entity E ON E.EntityOID = U.EntityOID
INNER JOIN Priority P ON P.PriorityOID = T.PriorityOID
INNER JOIN Frequency F ON F.FrequencyOID = T.FrequencyOID
INNER JOIN ConditionalTaskLog TL ON TL.UnitTaskOID = UT.UnitTaskOID
LEFT OUTER JOIN ConditionalMakerChecker TblLOGTMakerChecker ON TL.OID = TblLOGTMakerChecker.ConditionalOID
AND TblLOGTMakerChecker.STATUS = 0
LEFT OUTER JOIN TaskComplianceStatusValue TCSV ON TL.TaskComplianceStatusValueOID = TCSV.OID
INNER JOIN LTGN_USER_DETAIL UDFH ON UDFH.USER_OID = D.DeptHeadOID
LEFT OUTER JOIN LTGN_USER_DETAIL UDSup ON UDSup.USER_OID = TL.DeptSupervisorOID
INNER JOIN LTGN_USER_DETAIL UDPer ON UDPer.USER_OID = TL.PerformerUserOID
LEFT OUTER JOIN LTGN_USER_DETAIL UDComp ON UDComp.USER_OID = TL.CompletedByUserOID
WHERE UT.[Status] = 'Active'
AND UT.TaskStatus = 'Assigned'
AND T.Devices = 'No'
AND T.Title <> 'Applicability'
AND L.LegislationCategoryOID NOT IN(117, 118, 119, 120, 121, 122, 123, 124, 125)
AND T.CentralTaskOID NOT IN
(
SELECT CentralTaskOID
FROM GroupTask
)
AND U.EntityOID IN(27, 25, 26, 24)
AND u.UnitOID = UT.UnitOID
AND ((TL.ReviewerDt >= '12/17/2019'
AND TL.ReviewerDt <= '03/17/2020'
AND TL.PerformerDt <= '03/17/2020')
OR (TL.CompletedDt BETWEEN '12/17/2019' AND '03/17/2020')
OR (TL.ApproverDt >= '12/17/2019'
AND TL.ApproverDt <= '03/17/2020'))
UNION ALL
SELECT TL.OID,
E.EntityOID,
U.UnitOID,
D.DeptOID,
E.EntityName,
U.UnitName,
D.DeptName,
(CASE
WHEN ISNULL(LTRIM(RTRIM(U.ShortDesc)), '') = ''
THEN CONVERT(VARCHAR(50), UT.UnitTaskOID)
ELSE U.ShortDesc + '-' + CONVERT(VARCHAR(50), UT.UnitTaskOID)
END) AS 'UnitTaskWithDesc',
UT.[UnitTaskOID],
UT.[TaskOID],
T.LegislationOID,
T.CentralTaskOID,
L.LegislationCategoryOID,
C.LegislationCategory,
ISNULL(
(
SELECT C.CompanyCategory
FROM CompanyCategory C
WHERE C.CompanyCategoryOID = T.CompanyCategoryOID
), '-') CompanyCategory,
L.CentralState,
L.LegislationName,
T.Section_Rule_Regulation_Notification,
S.STATE_OID,
S.STATE_NAME,
T.[Title],
T.[PriorityOID],
P.Priority,
T.[FrequencyOID],
F.Frequency,
T.[Devices],
T.[Section_Rule_Regulation_Notification],
T.[Requirement_Apply],
T.[Task],
T.[Regulating_Authority],
T.[Consequences],
T.[Department],
TL.[Status] AS TaskStatus,
UT.PerformerUserOID,
D.DeptHeadOID,
ISNULL((UDFH.FIRST_NAME + ' ' + UDFH.LAST_NAME), '-') AS 'DeptHead',
UT.DeptSupervisorOID,
ISNULL((UDSup.FIRST_NAME + ' ' + UDSup.LAST_NAME), '-') AS 'Supervisor',
TL.PerformerUserOID AS 'PerformerUserOID_log',
ISNULL((UDPer.FIRST_NAME + ' ' + UDPer.LAST_NAME), '-') AS 'Performer',
ISNULL((UDComp.FIRST_NAME + ' ' + UDComp.LAST_NAME), '-') AS 'TaskCompletedBy',
dbo.FormatDate(#ClientCode, TL.ApproverDt) AS 'ApproverDt',
dbo.FormatDate(#ClientCode, TL.ReviewerDt) AS 'ReviewerDt',
dbo.FormatDate(#ClientCode, TL.SupervisorDt) AS 'SupervisorDt',
dbo.FormatDate(#ClientCode, TL.PerformerDt) AS 'PerformerDt',
CASE
WHEN #DeviationFunctionality = 'Yes'
THEN ISNULL(TL.Deviation, '-')
ELSE ''
END AS 'Deviation',
dbo.FormatDate(#ClientCode, TL.PerformedOnDt) AS 'PerformedOnDt',
dbo.FormatDate(#ClientCode, TL.CompletedDt) AS 'CompletedDt',
ISNULL(TL.Comments, '-') AS 'Comments',
('-') AS 'ActivationComment',
ISNULL(TL.ReasonForNonComp, '-') AS 'ReasonForNonComp',
ISNULL(TL.ActionTaken, '-') AS 'ActionTaken',
dbo.GetCompletionDate(#ClientCode, TL.CompletedDt, #ShowPerformedOnDate, #NoOfColorsInDashboardGraphs, TL.PerformedOnDt) AS 'Completed On',
dbo.GetCompletionComment('', TL.Comments, TL.ReviewerComment, TL.CompletedDt, TL.ReviewerCommentDate, TL.PeriodFromDate, TL.PeriodToDate) AS 'CompletionComments',
'' AS UnitDeviceOID,
'' AS TaskDeviceOID,
'' AS 'lblUnitDeviceOIDDesc',
dbo.GetComplianceStatus(TL.[Status], CONVERT(DATETIME, CONVERT(VARCHAR(50), TL.ApproverDt, 112)), CONVERT(DATETIME, CONVERT(VARCHAR(50), TL.CompletedDt, 112)), #NoOfColorsInDashboardGraphs, #TerminologyToNonCompliedCompletedTasks, #TerminologyToNonCompliedNonCompletedTasks, CONVERT(DATETIME, CONVERT(VARCHAR(50), TL.PerformedOnDt, 112)), #ShowPerformedOnDate, #TerminologyToNonCompliedCompletedTasksPerformedOnDtAfterDueDt, #TerminologyToCompliedTasks, #TerminologyToPosingRiskTasks) AS 'ComplianceStatus',
ISNULL(TblLOGTMakerChecker.RoutineTaskOID, 0) AS MKOID,
ISNULL(TCSV.TaskComplianceStatusValue, '-') AS TaskComplianceStatusValue,
ISNULL(TL.TaskComplianceStatusValueOID, 0) AS TaskComplianceStatusValueOID,
#NoOfColorsInDashboardGraphs AS 'NoOfColorsOnReport',
#TerminologyToNonCompliedCompletedTasks AS 'TerminologyToNonCompliedCompletedTask',
#TerminologyToNonCompliedNonCompletedTasks AS 'TerminologyToNonCompliedNonCompletedTask',
#ShowPerformedOnDate AS 'ShowPerformedOnDate',
#TerminologyToNonCompliedCompletedTasksPerformedOnDtAfterDueDt AS 'TerminologyToNonCompliedCompletedTasksPerformedOnDtAfterDueDt',
#TerminologyToCompliedTasks AS 'TerminologyToCompliedTasks',
(CASE
WHEN(
(
SELECT COUNT(*)
FROM UnitTaskDocs
WHERE UnitTaskOID = UT.UnitTaskOID
AND DueDateId = TL.OID
) > 0)
THEN 'Yes'
ELSE 'No'
END) AS 'DocumentUploaded',
dbo.FormatDate
(#ClientCode,
(
SELECT TOP 1 UPLOADED_DATE
FROM UnitTaskDocs
WHERE UnitTaskOID = UT.UnitTaskOID
AND DueDateId = TL.OID
ORDER BY 1 DESC
)
) AS 'DocUploadedDate',
(CASE
WHEN(
(
SELECT COUNT(*)
FROM UnitTaskDoc_Reminder
WHERE UnitTaskOID = UT.UnitTaskOID
AND RoutineTaskOID = TL.OID
) > 0)
THEN 'Yes'
ELSE 'No'
END) AS 'DocumentUploadLater',
TL.FeesPaid,
TL.PenaltyPaid,
TL.SecondSupervisorComment,
TL.SecondSupervisorCommentDate,
TL.ThirdSupervisorComment,
TL.ThirdSupervisorCommentDate,
'' AS TaskType,
'-' AS Region,
'-' AS SubRegion
FROM UnitTask UT
INNER JOIN Task T ON T.Task_OID = UT.TaskOID
INNER JOIN LegislationNames L ON L.LegislationOID = T.LegislationOID
INNER JOIN LegislationCategories C ON C.LegislationCategoryOID = L.LegislationCategoryOID
INNER JOIN [STATE] S ON S.STATE_OID = L.StateOID
INNER JOIN Dept D ON D.DeptOID = UT.PerformerDeptOID
INNER JOIN Units U ON U.UnitOID = UT.UnitOID
INNER JOIN Entity E ON E.EntityOID = U.EntityOID
INNER JOIN Priority P ON P.PriorityOID = T.PriorityOID
INNER JOIN Frequency F ON F.FrequencyOID = T.FrequencyOID
INNER JOIN RoutineTaskLog TL ON TL.UnitTaskOID = UT.UnitTaskOID
LEFT OUTER JOIN RoutineMakerChecker TblLOGTMakerChecker ON TL.OID = TblLOGTMakerChecker.RoutineTaskOID
AND TblLOGTMakerChecker.STATUS = 0
LEFT OUTER JOIN TaskComplianceStatusValue TCSV ON TL.TaskComplianceStatusValueOID = TCSV.OID
INNER JOIN LTGN_USER_DETAIL UDFH ON UDFH.USER_OID = D.DeptHeadOID
LEFT OUTER JOIN LTGN_USER_DETAIL UDSup ON UDSup.USER_OID = TL.DeptSupervisorOID
INNER JOIN LTGN_USER_DETAIL UDPer ON UDPer.USER_OID = TL.PerformerUserOID
LEFT OUTER JOIN LTGN_USER_DETAIL UDComp ON UDComp.USER_OID = TL.CompletedByUserOID
WHERE UT.[Status] = 'Active'
AND UT.TaskStatus = 'Assigned'
AND T.Devices = 'No'
AND T.Title <> 'Applicability'
AND L.LegislationCategoryOID NOT IN(117, 118, 119, 120, 121, 122, 123, 124, 125)
AND T.CentralTaskOID NOT IN
(
SELECT CentralTaskOID
FROM GroupTask
)
AND U.EntityOID IN(27, 25, 26, 24)
AND u.UnitOID = UT.UnitOID
AND ((TL.ReviewerDt >= '12/17/2019'
AND TL.ReviewerDt <= '03/17/2020'
AND TL.PerformerDt <= '03/17/2020')
OR (TL.CompletedDt BETWEEN '12/17/2019' AND '03/17/2020')
OR (TL.ApproverDt >= '12/17/2019'
AND TL.ApproverDt <= '03/17/2020'))
UNION ALL
SELECT TL.DailyTaskOID AS OID,
E.EntityOID,
U.UnitOID,
D.DeptOID,
E.EntityName,
U.UnitName,
D.DeptName,
(CASE
WHEN ISNULL(LTRIM(RTRIM(U.ShortDesc)), '') = ''
THEN CONVERT(VARCHAR(50), UT.UnitTaskOID)
ELSE U.ShortDesc + '-' + CONVERT(VARCHAR(50), UT.UnitTaskOID)
END) AS 'UnitTaskWithDesc',
UT.[UnitTaskOID],
UT.[TaskOID],
T.LegislationOID,
T.CentralTaskOID,
L.LegislationCategoryOID,
C.LegislationCategory,
ISNULL(
(
SELECT C.CompanyCategory
FROM CompanyCategory C
WHERE C.CompanyCategoryOID = T.CompanyCategoryOID
), '-') CompanyCategory,
L.CentralState,
L.LegislationName,
T.Section_Rule_Regulation_Notification,
S.STATE_OID,
S.STATE_NAME,
T.[Title],
T.[PriorityOID],
P.Priority,
T.[FrequencyOID],
F.Frequency,
T.[Devices],
T.[Section_Rule_Regulation_Notification],
T.[Requirement_Apply],
T.[Task],
T.[Regulating_Authority],
T.[Consequences],
T.[Department],
TL.[Status] AS TaskStatus,
UT.PerformerUserOID,
D.DeptHeadOID,
ISNULL((UDFH.FIRST_NAME + ' ' + UDFH.LAST_NAME), '-') AS 'DeptHead',
UT.DeptSupervisorOID,
ISNULL((UDSup.FIRST_NAME + ' ' + UDSup.LAST_NAME), '-') AS 'Supervisor',
TL.PerformerUserOID AS 'PerformerUserOID_log',
ISNULL((UDPer.FIRST_NAME + ' ' + UDPer.LAST_NAME), '-') AS 'Performer',
ISNULL((UDComp.FIRST_NAME + ' ' + UDComp.LAST_NAME), '-') AS 'TaskCompletedBy',
dbo.FormatDate(#ClientCode, TL.ApproverDt) AS 'ApproverDt',
dbo.FormatDate(#ClientCode, TL.ReviewerDt) AS 'ReviewerDt',
dbo.FormatDate(#ClientCode, TL.SupervisorDt) AS 'SupervisorDt',
dbo.FormatDate(#ClientCode, TL.PerformerDt) AS 'PerformerDt',
CASE
WHEN #DeviationFunctionality = 'Yes'
THEN ISNULL(TL.Deviation, '-')
ELSE ''
END AS 'Deviation',
dbo.FormatDate(#ClientCode, TL.PerformedOnDt) AS 'PerformedOnDt',
dbo.FormatDate(#ClientCode, TL.CompletedDt) AS 'CompletedDt',
ISNULL(TL.Comments, '-') AS 'Comments',
('-') AS 'ActivationComment',
ISNULL(TL.ReasonForNonComp, '-') AS 'ReasonForNonComp',
ISNULL(TL.ActionTaken, '-') AS 'ActionTaken',
dbo.GetCompletionDate(#ClientCode, TL.CompletedDt, #ShowPerformedOnDate, #NoOfColorsInDashboardGraphs, TL.PerformedOnDt) AS 'Completed On',
dbo.GetCompletionComment('', TL.Comments, TL.ReviewerComment, TL.CompletedDt, TL.ReviewerCommentDate, TL.PeriodFromDate, TL.PeriodToDate) AS 'CompletionComments',
'' AS UnitDeviceOID,
'' AS TaskDeviceOID,
'' AS 'lblUnitDeviceOIDDesc',
dbo.GetComplianceStatus(TL.[Status], CONVERT(DATETIME, CONVERT(VARCHAR(50), TL.ApproverDt, 112)), CONVERT(DATETIME, CONVERT(VARCHAR(50), TL.CompletedDt, 112)), #NoOfColorsInDashboardGraphs, #TerminologyToNonCompliedCompletedTasks, #TerminologyToNonCompliedNonCompletedTasks, CONVERT(DATETIME, CONVERT(VARCHAR(50), TL.PerformedOnDt, 112)), #ShowPerformedOnDate, #TerminologyToNonCompliedCompletedTasksPerformedOnDtAfterDueDt, #TerminologyToCompliedTasks, #TerminologyToPosingRiskTasks) AS 'ComplianceStatus',
ISNULL(TblLOGTMakerChecker.DailyTaskOID, 0) AS MKOID,
ISNULL(TCSV.TaskComplianceStatusValue, '-') AS TaskComplianceStatusValue,
ISNULL(TL.TaskComplianceStatusValueOID, 0) AS TaskComplianceStatusValueOID,
#NoOfColorsInDashboardGraphs AS 'NoOfColorsOnReport',
#TerminologyToNonCompliedCompletedTasks AS 'TerminologyToNonCompliedCompletedTask',
#TerminologyToNonCompliedNonCompletedTasks AS 'TerminologyToNonCompliedNonCompletedTask',
#ShowPerformedOnDate AS 'ShowPerformedOnDate',
#TerminologyToNonCompliedCompletedTasksPerformedOnDtAfterDueDt AS 'TerminologyToNonCompliedCompletedTasksPerformedOnDtAfterDueDt',
#TerminologyToCompliedTasks AS 'TerminologyToCompliedTasks',
(CASE
WHEN(
Yes, you cannot declare variables in a view.

Hard Query with SqlServer (with When and else)

i have a query but i don't know why it is bad.
The error is: SQL (4104): Invalid column name 'CUSTOMDATA2' The multi-part identifier "PCO.QUALIFICATIONCODE.code" could not be bound, but i don't uderstand where and why it is bad.
I am very lost with this query :/, some guru of querys can i help me ?.
Edited query for dont hurt people.
Thank you in advance.
SELECT PCO_QUALIFICATIONCODE.CODE,
CASE
WHEN (ActividadesActivas.[CUSTOMDATA2] IS NULL)
THEN
(SELECT Description
FROM PCO_QUALIFICATIONCODE BIS
WHERE SERVICEID = 1
AND BIS.CODE = SUBSTRING(CAST(PCO_QUALIFICATIONCODE.CODE AS VARCHAR), 1, 3)
)
ELSE ActividadesActivas.[CUSTOMDATA2]
END CUSTOMDATA2,
CASE
WHEN (ActividadesActivas.[CUSTOMDATA3] IS NULL)
THEN
CASE
WHEN (SUBSTRING(CAST(CODE AS VARCHAR), 5, 1) <> '')
THEN
(SELECT Description
FROM PCO_QUALIFICATIONCODE BIS
WHERE SERVICEID = 1
AND BIS.CODE = SUBSTRING(CAST(PCO_QUALIFICATIONCODE.CODE AS VARCHAR), 1, 5)
)
WHEN (SUBSTRING(CAST(CODE AS VARCHAR), 4, 1) <> '')
THEN
(SELECT Description
FROM PCO_QUALIFICATIONCODE BIS
WHERE SERVICEID = 1
AND BIS.CODE = SUBSTRING(CAST(PCO_QUALIFICATIONCODE.CODE AS VARCHAR), 1, 4)
)
WHEN ActividadesActivas.[CUSTOMDATA3] IS NULL
OR ActividadesActivas.[CUSTOMDATA3] = 'NULL'
THEN ''
ELSE ActividadesActivas.[CUSTOMDATA3]
END
ELSE ActividadesActivas.[CUSTOMDATA3]
END CUSTOMDATA3,
Totales.TOTAL
FROM [SQLPR1].[PREP].PCO_QUALIFICATIONCODE
LEFT JOIN
(SELECT [QCODE],
CASE
WHEN ((SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3) IS NOT NULL)
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 4, 1) = '')
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 5, 1) = '') )
THEN
(SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3)
)
WHEN ((SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3) IS NOT NULL)
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 4, 1) <> '')
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 5, 1) = '') )
THEN
(SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3)
)
WHEN ((SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3) IS NOT NULL)
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 4, 1) <> '')
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 5, 1) <> '') )
THEN
(SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3)
)
END CUSTOMDATA2,
CASE
WHEN ((SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3) IS NOT NULL)
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 4, 1) = '')
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 5, 1) = '') )
THEN
CASE
WHEN CUSTOMDATA3 IS NULL
OR CUSTOMDATA3 = 'NULL'
THEN ''
ELSE CUSTOMDATA3
END
WHEN ((SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3) IS NOT NULL)
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 4, 1) <> '')
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 5, 1) = '') )
THEN
(SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 4)
)
WHEN ((SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3) IS NOT NULL)
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 4, 1) <> '')
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 5, 1) <> '') )
THEN
CASE
WHEN (SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 4)) IS NOT NULL
THEN
(SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 4)
) + ' / ' +
(SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 5)
)
ELSE
(SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 5)
)
END
ELSE ''
END CUSTOMDATA3
FROM [SQLPR1].[PREP].[PCO_INBOUNDLOG]
WHERE SERVICEID = 1
AND QCODE > 9
GROUP BY QCODE,
CUSTOMDATA2,
CUSTOMDATA3
) ActividadesActivas
ON PCO_QUALIFICATIONCODE.CODE = ActividadesActivas.QCODE
LEFT JOIN
(SELECT [QCODE],
CASE
WHEN ((SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3) IS NOT NULL)
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 4, 1) = '')
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 5, 1) = '') )
THEN
(SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3)
)
WHEN ((SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3) IS NOT NULL)
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 4, 1) <> '')
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 5, 1) = '') )
THEN
(SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3)
)
WHEN ((SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3) IS NOT NULL)
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 4, 1) <> '')
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 5, 1) <> '') )
THEN
(SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3)
)
END CUSTOMDATA2,
CASE
WHEN ((SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3) IS NOT NULL)
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 4, 1) = '')
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 5, 1) = '') )
THEN
CASE
WHEN CUSTOMDATA3 IS NULL
OR CUSTOMDATA3 = 'NULL'
THEN ''
ELSE CUSTOMDATA3
END
WHEN ((SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3) IS NOT NULL)
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 4, 1) <> '')
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 5, 1) = '') )
THEN
(SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 4)
)
WHEN ((SUBSTRING(CAST(QCODE AS VARCHAR), 1, 3) IS NOT NULL)
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 4, 1) <> '')
AND (SUBSTRING(CAST(QCODE AS VARCHAR), 5, 1) <> '') )
THEN
CASE
WHEN (SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 4)) IS NOT NULL
THEN
(SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 4)
) + ' / ' +
(SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 5)
)
ELSE
(SELECT Description
FROM PCO_QUALIFICATIONCODE
WHERE SERVICEID = 1
AND CODE = SUBSTRING(CAST(QCODE AS VARCHAR), 1, 5)
)
END
ELSE ''
END CUSTOMDATA3,
COUNT(*) TOTAL
FROM [SQLPR1].[PREP].[PCO_INBOUNDLOG]
WHERE [SERVICEID] = 1
AND RDATE BETWEEN '2017/02/01 00:00:00' AND '2018/02/20 23:59:59'
GROUP BY QCODE,
CUSTOMDATA2,
CUSTOMDATA3
) Totales
ON ActividadesActivas.QCODE = Totales.QCODE
AND ActividadesActivas.CUSTOMDATA2 = Totales.CUSTOMDATA2
AND ActividadesActivas.CUSTOMDATA3 = Totales.CUSTOMDATA3
WHERE SERVICEID = 1
AND PCO_QUALIFICATIONCODE.CODE NOT IN (102,103,104,105,106,107,113)
GROUP BY PCO_QUALIFICATIONCODE.CODE,
ActividadesActivas.CUSTOMDATA2,
ActividadesActivas.CUSTOMDATA3,
Totales.TOTAL
ORDER BY CAST(PCO_QUALIFICATIONCODE.CODE AS VARCHAR),
CUSTOMDATA2
Your problem here is in the group by.
You are masking your field "ActividadesActivas.[CUSTOMDATA2]" with "CUSTOMDATA2"
CASE
WHEN (ActividadesActivas.[CUSTOMDATA2] IS NULL)
THEN
(SELECT Description
FROM PCO_QUALIFICATIONCODE BIS
WHERE SERVICEID = 1
AND BIS.CODE = SUBSTRING(CAST(PCO_QUALIFICATIONCODE.CODE AS VARCHAR), 1, 3)
)
ELSE ActividadesActivas.[CUSTOMDATA2]
END CUSTOMDATA2,
so, in the group by, you can only use "CUSTOMDATA2" and not "ActividadesActivas.[CUSTOMDATA2]"
GROUP BY PCO_QUALIFICATIONCODE.CODE,
ActividadesActivas.CUSTOMDATA2,
ActividadesActivas.CUSTOMDATA3,
Totales.TOTAL
PS: same rule should apply to remaining fields.
EDIT: I'm not sure if that is the only issue with your query, but that is the reason for your issue "Invalid column name 'CUSTOMDATA2'"

Is there a way to prevent SQL Server from automatically formatting my view query?

It's ok to have a common format, I have mine, me and my team uses the same format when writing SQL.
Now here is the problem: we use SQL Server. I wrote a long view, then, to remember what I did, I opened the "design" of that view. And I noticed that SQL Server completely screwed my format, and applied its own. Even worse, it duplicate simple conditions and make them longer for no reason (maybe I'm judging a bit to fast... but...)
Here is my example, sorry it's a very long condition, you don't have to read it, just notice the format:
WHERE (STATUT_CAND IN (2, 3))
AND
(DATE_DISPO < GETDATE() OR DATE_DISPO IS NULL)
AND
((SELECT COUNT(ID_CAND) AS Expr1
FROM Paie.dbo.PAI_CAND_RESULT_ENTREVUE AS pcre
WHERE (ID_CAND = PC.ID_CAND)) > 0)
AND
((SELECT COUNT(MATR) AS Expr1
FROM Paie.dbo.PAI_DOS_EMPL AS PAI_DOS_EMPL_1
WHERE (MATR = PC.MATR) AND (ETAT = 'C14' OR
ETAT = 'C15' OR
ETAT = 'E1') OR
(MATR = PC.MATR) AND (ETAT LIKE 'A%' OR
ETAT LIKE 'P%' OR
ETAT LIKE 'S%') AND (STAT_ENG = 'E1' OR
STAT_ENG = 'P1' OR
STAT_ENG = 'G1')) <= 0)
AND
(NOT EXISTS
(SELECT ID_CAND
FROM Paie.dbo.PAI_CAND_EMPL AS PAI_CAND_EMPL_1
WHERE (ID_CAND = PC.ID_CAND) AND (MOTIF_EXCLUS IS NOT NULL) AND (MOTIF_EXCLUS NOT IN ('0'))))
AND (NOT EXISTS
(SELECT MOT_ABS
FROM Paie.dbo.PAI_DOS_PMNT_ABS AS PAI_DOS_PMNT_ABS_1
WHERE (MATR = PC.MATR) AND (MOT_ABS = '15' OR
MOT_ABS = '16' OR
MOT_ABS = '40' OR
MOT_ABS = '41' OR
MOT_ABS = '45' OR
MOT_ABS = '46' OR
MOT_ABS >= '52' AND MOT_ABS <= '57') OR
(MATR = PC.MATR) AND (MOT_ABS = '01') AND (CODE_PMNT >= 103522 AND CODE_PMNT <= 103541 OR
CODE_PMNT = 103572 OR
CODE_PMNT = 103573 OR
CODE_PMNT = 103577)))
AND (NOT EXISTS
(SELECT STAT_ENG
FROM Paie.dbo.PAI_DOS_EMPL AS pados
WHERE (MATR = PC.MATR) AND (DATE_EFF > GETDATE())))
AND (NOT EXISTS
(SELECT MOTIF_AFF
FROM Paie.dbo.GRH_POSTE_AFFECT AS pados
WHERE (PC.MATR = MATR) AND (MOTIF_AFF LIKE '%S%') AND (DATE_EFF =
(SELECT MAX(DATE_EFF) AS Expr1
FROM Paie.dbo.GRH_POSTE_AFFECT AS aff
WHERE (MATR = PC.MATR)))))
AND ( EXISTS
(SELECT MATR
FROM Paie.dbo.PAI_HCHQ_PMNT AS dosem
WHERE (MATR = PC.MATR) AND (DATE_FIN > DATEADD (year , -3 , GETDATE() ))) or (select DATE_DERN_PAIE from paie.dbo.PAI_DOS where MATR = PC.MATR) > DATEADD (year , -3 , GETDATE() ) or (select DATE_DERN_PAIE from paie.dbo.PAI_DOS where MATR = PC.MATR) is null)
This way, I know where the MAIN AND are, now when I put this into the view, this is how SQL Server format it :
WHERE (STATUT_CAND IN (2, 3)) AND (DATE_DISPO < GETDATE() OR
DATE_DISPO IS NULL) AND
((SELECT COUNT(ID_CAND) AS Expr1
FROM Paie.dbo.PAI_CAND_RESULT_ENTREVUE AS pcre
WHERE (ID_CAND = PC.ID_CAND)) > 0) AND
((SELECT COUNT(MATR) AS Expr1
FROM Paie.dbo.PAI_DOS_EMPL AS PAI_DOS_EMPL_1
WHERE (MATR = PC.MATR) AND (ETAT = 'C14' OR
ETAT = 'C15' OR
ETAT = 'E1') OR
(MATR = PC.MATR) AND (ETAT LIKE 'A%' OR
ETAT LIKE 'P%' OR
ETAT LIKE 'S%') AND (STAT_ENG = 'E1' OR
STAT_ENG = 'P1' OR
STAT_ENG = 'G1')) <= 0) AND (NOT EXISTS
(SELECT ID_CAND
FROM Paie.dbo.PAI_CAND_EMPL AS PAI_CAND_EMPL_1
WHERE (ID_CAND = PC.ID_CAND) AND (MOTIF_EXCLUS IS NOT NULL) AND (MOTIF_EXCLUS NOT IN ('0')))) AND (NOT EXISTS
(SELECT MOT_ABS
FROM Paie.dbo.PAI_DOS_PMNT_ABS AS PAI_DOS_PMNT_ABS_1
WHERE (MATR = PC.MATR) AND (MOT_ABS = '15' OR
MOT_ABS = '16' OR
MOT_ABS = '40' OR
MOT_ABS = '41' OR
MOT_ABS = '45' OR
MOT_ABS = '46' OR
MOT_ABS >= '52' AND MOT_ABS <= '57') OR
(MATR = PC.MATR) AND (MOT_ABS = '01') AND (CODE_PMNT >= 103522 AND CODE_PMNT <= 103541 OR
CODE_PMNT = 103572 OR
CODE_PMNT = 103573 OR
CODE_PMNT = 103577))) AND (NOT EXISTS
(SELECT STAT_ENG
FROM Paie.dbo.PAI_DOS_EMPL AS pados
WHERE (MATR = PC.MATR) AND (DATE_EFF > GETDATE()))) AND (NOT EXISTS
(SELECT MOTIF_AFF
FROM Paie.dbo.GRH_POSTE_AFFECT AS pados
WHERE (PC.MATR = MATR) AND (MOTIF_AFF LIKE '%S%') AND (DATE_EFF =
(SELECT MAX(DATE_EFF) AS Expr1
FROM Paie.dbo.GRH_POSTE_AFFECT AS aff
WHERE (MATR = PC.MATR))))) AND EXISTS
(SELECT MATR
FROM Paie.dbo.PAI_HCHQ_PMNT AS dosem
WHERE (MATR = PC.MATR) AND (DATE_FIN > DATEADD(year, - 3, GETDATE()))) OR
(STATUT_CAND IN (2, 3)) AND (DATE_DISPO < GETDATE() OR
DATE_DISPO IS NULL) AND
((SELECT COUNT(ID_CAND) AS Expr1
FROM Paie.dbo.PAI_CAND_RESULT_ENTREVUE AS pcre
WHERE (ID_CAND = PC.ID_CAND)) > 0) AND
((SELECT COUNT(MATR) AS Expr1
FROM Paie.dbo.PAI_DOS_EMPL AS PAI_DOS_EMPL_1
WHERE (MATR = PC.MATR) AND (ETAT = 'C14' OR
ETAT = 'C15' OR
ETAT = 'E1') OR
(MATR = PC.MATR) AND (ETAT LIKE 'A%' OR
ETAT LIKE 'P%' OR
ETAT LIKE 'S%') AND (STAT_ENG = 'E1' OR
STAT_ENG = 'P1' OR
STAT_ENG = 'G1')) <= 0) AND (NOT EXISTS
(SELECT ID_CAND
FROM Paie.dbo.PAI_CAND_EMPL AS PAI_CAND_EMPL_1
WHERE (ID_CAND = PC.ID_CAND) AND (MOTIF_EXCLUS IS NOT NULL) AND (MOTIF_EXCLUS NOT IN ('0')))) AND (NOT EXISTS
(SELECT MOT_ABS
FROM Paie.dbo.PAI_DOS_PMNT_ABS AS PAI_DOS_PMNT_ABS_1
WHERE (MATR = PC.MATR) AND (MOT_ABS = '15' OR
MOT_ABS = '16' OR
MOT_ABS = '40' OR
MOT_ABS = '41' OR
MOT_ABS = '45' OR
MOT_ABS = '46' OR
MOT_ABS >= '52' AND MOT_ABS <= '57') OR
(MATR = PC.MATR) AND (MOT_ABS = '01') AND (CODE_PMNT >= 103522 AND CODE_PMNT <= 103541 OR
CODE_PMNT = 103572 OR
CODE_PMNT = 103573 OR
CODE_PMNT = 103577))) AND (NOT EXISTS
(SELECT STAT_ENG
FROM Paie.dbo.PAI_DOS_EMPL AS pados
WHERE (MATR = PC.MATR) AND (DATE_EFF > GETDATE()))) AND (NOT EXISTS
(SELECT MOTIF_AFF
FROM Paie.dbo.GRH_POSTE_AFFECT AS pados
WHERE (PC.MATR = MATR) AND (MOTIF_AFF LIKE '%S%') AND (DATE_EFF =
(SELECT MAX(DATE_EFF) AS Expr1
FROM Paie.dbo.GRH_POSTE_AFFECT AS aff
WHERE (MATR = PC.MATR))))) AND
((SELECT DATE_DERN_PAIE
FROM Paie.dbo.PAI_DOS
WHERE (MATR = PC.MATR)) > DATEADD(year, - 3, GETDATE())) OR
(STATUT_CAND IN (2, 3)) AND (DATE_DISPO < GETDATE() OR
DATE_DISPO IS NULL) AND
((SELECT COUNT(ID_CAND) AS Expr1
FROM Paie.dbo.PAI_CAND_RESULT_ENTREVUE AS pcre
WHERE (ID_CAND = PC.ID_CAND)) > 0) AND
((SELECT COUNT(MATR) AS Expr1
FROM Paie.dbo.PAI_DOS_EMPL AS PAI_DOS_EMPL_1
WHERE (MATR = PC.MATR) AND (ETAT = 'C14' OR
ETAT = 'C15' OR
ETAT = 'E1') OR
(MATR = PC.MATR) AND (ETAT LIKE 'A%' OR
ETAT LIKE 'P%' OR
ETAT LIKE 'S%') AND (STAT_ENG = 'E1' OR
STAT_ENG = 'P1' OR
STAT_ENG = 'G1')) <= 0) AND (NOT EXISTS
(SELECT ID_CAND
FROM Paie.dbo.PAI_CAND_EMPL AS PAI_CAND_EMPL_1
WHERE (ID_CAND = PC.ID_CAND) AND (MOTIF_EXCLUS IS NOT NULL) AND (MOTIF_EXCLUS NOT IN ('0')))) AND (NOT EXISTS
(SELECT MOT_ABS
FROM Paie.dbo.PAI_DOS_PMNT_ABS AS PAI_DOS_PMNT_ABS_1
WHERE (MATR = PC.MATR) AND (MOT_ABS = '15' OR
MOT_ABS = '16' OR
MOT_ABS = '40' OR
MOT_ABS = '41' OR
MOT_ABS = '45' OR
MOT_ABS = '46' OR
MOT_ABS >= '52' AND MOT_ABS <= '57') OR
(MATR = PC.MATR) AND (MOT_ABS = '01') AND (CODE_PMNT >= 103522 AND CODE_PMNT <= 103541 OR
CODE_PMNT = 103572 OR
CODE_PMNT = 103573 OR
CODE_PMNT = 103577))) AND (NOT EXISTS
(SELECT STAT_ENG
FROM Paie.dbo.PAI_DOS_EMPL AS pados
WHERE (MATR = PC.MATR) AND (DATE_EFF > GETDATE()))) AND (NOT EXISTS
(SELECT MOTIF_AFF
FROM Paie.dbo.GRH_POSTE_AFFECT AS pados
WHERE (PC.MATR = MATR) AND (MOTIF_AFF LIKE '%S%') AND (DATE_EFF =
(SELECT MAX(DATE_EFF) AS Expr1
FROM Paie.dbo.GRH_POSTE_AFFECT AS aff
WHERE (MATR = PC.MATR))))) AND
((SELECT DATE_DERN_PAIE
FROM Paie.dbo.PAI_DOS AS PAI_DOS_1
Not only is it almost impossible to understand anything (personally I don't) BUT IT IS 3 TIMES LONGER THEN THE ONE I WROTE... Unacceptable, is there a way to turn auto format off? If not I'm going to keep my format in a separate file and copy paste it every time.
Don't use the designer. It does horrible things to formatting. Just right click and "script as create to new window". It will maintain your formatting. And as Aaron Bertrand commented you should avoid using any of the visual designers.

how to use coalesce with in, in the where part

How to use Coalesce Command in the following code
PIECE_DETAIL in coalesce( PIECE_DETAIL, (SELECT B.MODEL_ID FROM PIECES_DETAILS B WHERE PIECE_ID = #PIECE_ID AND B.BRAND_ID=COALESCE(B.BRAND_ID,#BRAND_ID))
in this code
SELECT DISTINCT
[dbo].[test2](A.PIECE_DETAIL ) TOTAL_QUANTITY,
PIECE_LATIN = (SELECT PIECE_LATIN FROM PIECES WHERE PIECE_ID =
(SELECT PIECE_ID FROM PIECES_DETAILS WHERE MODEL_ID = A.PIECE_DETAIL )),
BRAND_LATIN = (SELECT BRAND_LATIN FROM BRANDS WHERE BRAND_ID =
(SELECT BRAND_ID FROM PIECES_DETAILS WHERE MODEL_ID = A.PIECE_DETAIL )),
BRAND_ID = (SELECT BRAND_ID FROM PIECES_DETAILS WHERE MODEL_ID = A.PIECE_DETAIL ),
PIECE_ID = (SELECT PIECE_ID FROM PIECES_DETAILS WHERE MODEL_ID = A.PIECE_DETAIL ),
MODEL_NAME = (SELECT MODEL_NAME FROM PIECES_DETAILS WHERE MODEL_ID = A.PIECE_DETAIL ),
PIECE_DETAIL MODEL_ID,
A.PIECE_STATUS ,
PIECE_STATUS_Name = (SELECT STATUS_Name FROM PIECE_STATUS WHERE STATUS_ID = A.PIECE_STATUS) ,
A.PIECE_DETAIL
FROM DOCUMENT_ITEMS A
WHERE
PIECE_STATUS = 1 and
DOC_SEQ IN (SELECT DOC_SEQ FROM DOCUMENT_HEADER WHERE DOC_TYPE IN (1,3))
AND PIECE_DETAIL in coalesce( PIECE_DETAIL, (SELECT B.MODEL_ID FROM PIECES_DETAILS B WHERE PIECE_ID = #PIECE_ID AND B.BRAND_ID=COALESCE(B.BRAND_ID,#BRAND_ID))
AND [DBO].[GET_WAREHOUSE_QUANTITIES_SPECIAL_ID_EXIST](A.PIECE_DETAIL ,A.SPECIAL_ID )> 0
GROUP BY PIECE_DETAIL ,SPECIAL_ID ,PIECE_STATUS
thanks all
Something like this then:
WHERE PIECE_DETAIL IN
(
SELECT
coalesce(PIECE_DETAIL,B.MODEL_ID)
FROM
PIECES_DETAILS B
WHERE
PIECE_ID = #PIECE_ID
AND B.BRAND_ID=COALESCE(B.BRAND_ID,#BRAND_ID)
)
Edit
Maybe something like this:
WHERE
(
(
FROM_DATE IS NULL AND TO_DATE IS NULL
)
OR
(
BUY_DOC_DATE BETWEEN FROM_DATE AND TO_DATE
)
)

Resources