SQL what is wrong with the syntax here? - sql

What is wrong with the syntax in this function? I am getting the following errors:
ALTER FUNCTION [dbo].[udf_ReportingLevelStructure2]
(
#CompanyID INT
)
RETURNS #result TABLE
(
CompanyName VARCHAR(300),
[rl_Index] INT,
[rl_Addr1] VARCHAR(MAX),
[rl_Addr2] VARCHAR(MAX),
[rl_DisplayName] VARCHAR(MAX)
)
AS
BEGIN
DECLARE #tmp1 TABLE
(
CompanyName VARCHAR(300),
[rl_Index] INT,
[rl_Addr1] VARCHAR(MAX),
[rl_Addr2] VARCHAR(MAX),
[rl_DisplayName] VARCHAR(MAX)
);
DECLARE #tmp2 TABLE
(
[CompanyName] VARCHAR(300),
[rl_Index] INT,
[rl_Addr1] VARCHAR(MAX),
[rl_Addr2] VARCHAR(MAX),
[rl_DisplayName] VARCHAR(MAX)
)
INSERT INTO #tmp1([CompanyName],[rl_Index],[rl_Addr1],[rl_Addr2],[rl_DisplayName])
(SELECT
rl0.[rl_Name] AS [CompanyName]
,rl_Index =
CASE
WHEN rl9.[rl_Name] IS NOT NULL THEN rl9.[rl_Index]
WHEN rl8.[rl_Name] IS NOT NULL THEN rl8.[rl_Index]
WHEN rl7.[rl_Name] IS NOT NULL THEN rl7.[rl_Index]
WHEN rl6.[rl_Name] IS NOT NULL THEN rl6.[rl_Index]
WHEN rl5.[rl_Name] IS NOT NULL THEN rl5.[rl_Index]
WHEN rl4.[rl_Name] IS NOT NULL THEN rl4.[rl_Index]
WHEN rl3.[rl_Name] IS NOT NULL THEN rl3.[rl_Index]
WHEN rl2.[rl_Name] IS NOT NULL THEN rl2.[rl_Index]
WHEN rl1.[rl_Name] IS NOT NULL THEN rl1.[rl_Index]
END
,rl_Addr1 =
CASE
WHEN rl9.[rl_Name] IS NOT NULL THEN rl9.[rl_Addr1]
WHEN rl8.[rl_Name] IS NOT NULL THEN rl8.[rl_Addr1]
WHEN rl7.[rl_Name] IS NOT NULL THEN rl7.[rl_Addr1]
WHEN rl6.[rl_Name] IS NOT NULL THEN rl6.[rl_Addr1]
WHEN rl5.[rl_Name] IS NOT NULL THEN rl5.[rl_Addr1]
WHEN rl4.[rl_Name]IS NOT NULL THEN rl4.[rl_Addr1]
WHEN rl3.[rl_Name] IS NOT NULL THEN rl3.[rl_Addr1]
WHEN rl2.[rl_Name] IS NOT NULL THEN rl2.[rl_Addr1]
WHEN rl1.[rl_Name] IS NOT NULL THEN rl1.[rl_Addr1]
END
,rl_Addr2 =
CASE
WHEN rl9.[rl_Name] IS NOT NULL THEN rl9.[rl_Addr2]
WHEN rl8.[rl_Name] IS NOT NULL THEN rl8.[rl_Addr2]
WHEN rl7.[rl_Name] IS NOT NULL THEN rl7.[rl_Addr2]
WHEN rl6.[rl_Name] IS NOT NULL THEN rl6.[rl_Addr2]
WHEN rl5.[rl_Name] IS NOT NULL THEN rl5.[rl_Addr2]
WHEN rl4.[rl_Name] IS NOT NULL THEN rl4.[rl_Addr2]
WHEN rl3.[rl_Name] IS NOT NULL THEN rl3.[rl_Addr2]
WHEN rl2.[rl_Name] IS NOT NULL THEN rl2.[rl_Addr2]
WHEN rl1.[rl_Name]IS NOT NULL THEN rl1.[rl_Addr2]
END
,CASE
WHEN rl9.[rl_Name] IS NOT NULL THEN rl1.[rl_Name]+'> '+rl2.[rl_Name]+'> '+rl3.[rl_Name]+'> '+rl4.[rl_Name]+'> '+ rl5.[rl_Name]+'> '+ rl6.[rl_Name]+'> '+rl7.[rl_Name]+'> '+ rl8.[rl_Name]+'> '+ rl9.[rl_Name]
WHEN rl8.[rl_Name] IS NOT NULL THEN rl1.[rl_Name]+'> '+rl2.[rl_Name]+'> '+rl3.[rl_Name]+'> '+rl4.[rl_Name]+'> '+ rl5.[rl_Name]+'> '+ rl6.[rl_Name]+'> '+rl7.[rl_Name]+'> '+ rl8.[rl_Name]
WHEN rl7.[rl_Name] IS NOT NULL THEN rl1.[rl_Name]+'> '+rl2.[rl_Name]+'> '+rl3.[rl_Name]+'> '+rl4.[rl_Name]+'> '+ rl5.[rl_Name]+'> '+ rl6.[rl_Name]+'> '+rl7.[rl_Name]
WHEN rl6.[rl_Name] IS NOT NULL THEN rl1.[rl_Name]+'> '+rl2.[rl_Name]+'> '+rl3.[rl_Name]+'> '+rl4.[rl_Name]+'> '+ rl5.[rl_Name]+'> '+ rl6.[rl_Name]
WHEN rl5.[rl_Name] IS NOT NULL THEN rl1.[rl_Name]+'> '+rl2.[rl_Name]+'> '+rl3.[rl_Name]+'> '+rl4.[rl_Name]+'> '+ rl5.[rl_Name]
WHEN rl4.[rl_Name] IS NOT NULL THEN rl1.[rl_Name]+'> '+rl2.[rl_Name]+'> '+rl3.[rl_Name]+'> '+rl4.[rl_Name]
WHEN rl3.[rl_Name] IS NOT NULL THEN rl1.[rl_Name]+'> '+rl2.[rl_Name]+'> '+rl3.[rl_Name]
WHEN rl2.[rl_Name] IS NOT NULL THEN rl1.[rl_Name]+'> '+rl2.[rl_Name]
WHEN rl1.[rl_Name] IS NOT NULL THEN rl1.[rl_Name]
END AS [rl_DisplayName]
FROM
dbo.[ReportingLevels] rl0
LEFT JOIN ReportingLevels rl1
ON (rl1.[rl_CompanyID] = #CompanyID
AND rl1.[rl_Indent1] <> 0
AND rl1.[rl_Indent2] = 0)
LEFT JOIN ReportingLevels rl2
ON (rl2.[rl_CompanyID] = #CompanyID
AND rl2.[rl_Indent1] = rl1.[rl_Indent1]
AND rl2.[rl_Indent2] <> 0
AND rl2.[rl_Indent3] = 0)
LEFT JOIN ReportingLevels rl3
ON (rl3.[rl_CompanyID] = #CompanyID
AND rl3.[rl_Indent2] = rl2.[rl_Indent2]
AND rl3.[rl_Indent1] = rl2.[rl_Indent1]
AND rl3.[rl_Indent3] <> 0
AND rl3.[rl_Indent4] = 0)
LEFT JOIN ReportingLevels rl4
ON (rl4.[rl_CompanyID] = #CompanyID
AND rl4.[rl_Indent3]= rl3.[rl_Indent3]
AND rl4.[rl_Indent2] = rl3.[rl_Indent2]
AND rl4.[rl_Indent1] = rl3.[rl_Indent1]
AND rl4.[rl_Indent4] <> 0
AND rl4.[rl_Indent5] = 0)
LEFT JOIN ReportingLevels rl5
ON (rl5.[rl_CompanyID] = #CompanyID
AND rl5.[rl_Indent4] = rl4.[rl_Indent4]
AND rl5.[rl_Indent3] = rl4.[rl_Indent3]
AND rl5.[rl_Indent2] = rl4.[rl_Indent2]
AND rl5.[rl_Indent1] = rl4.[rl_Indent1]
AND rl5.[rl_Indent5] <> 0
AND rl5.[rl_Indent6]= 0)
LEFT JOIN ReportingLevels rl6
ON (rl6.[rl_CompanyID] = #CompanyID
AND rl6.[rl_Indent5] = rl5.rl_Indent5
AND rl6.[rl_Indent4] = rl5.rl_Indent4
AND rl6.[rl_Indent3] = rl5.rl_Indent3
AND rl6.[rl_Indent2] = rl5.rl_Indent2
AND rl6.[rl_Indent1] = rl5.rl_Indent1
AND rl6.[rl_Indent6] <> 0
AND rl6.[rl_Indent7] = 0)
LEFT JOIN ReportingLevels rl7
ON (rl7.[rl_CompanyID] = #CompanyID
AND rl7.[rl_Indent6] = rl6.[rl_Indent6]
AND rl7.[rl_Indent5] = rl6.[rl_Indent5]
AND rl7.[rl_Indent4] = rl6.[rl_Indent4]
AND rl7.[rl_Indent3] = rl6.[rl_Indent3]
AND rl7.[rl_Indent2] = rl6.[rl_Indent2]
AND rl7.[rl_Indent1] = rl6.[rl_Indent1]
AND rl7.[rl_Indent7] <> 0
AND rl7.[rl_Indent8] = 0)
LEFT JOIN ReportingLevels rl8
ON (rl8.[rl_CompanyID] = #CompanyID
AND rl8.[rl_Indent7] = rl7.[rl_Indent7]
AND rl8.[rl_Indent6] = rl7.[rl_Indent6]
AND rl8.[rl_Indent5] = rl7.[rl_Indent5]
AND rl8.[rl_Indent4] = rl7.[rl_Indent4]
AND rl8.[rl_Indent3] = rl7.[rl_Indent3]
AND rl8.[rl_Indent2] = rl7.[rl_Indent2]
AND rl8.[rl_Indent1] = rl7.[rl_Indent1]
AND rl8.[rl_Indent8]<> 0
AND rl7.[rl_Indent9] = 0)
LEFT JOIN ReportingLevels rl9
ON (rl9.[rl_CompanyID] = #CompanyID
AND rl9.[rl_Indent8] = rl8.[rl_Indent8]
AND rl9.[rl_Indent7] = rl8.[rl_Indent7]
AND rl9.[rl_Indent6] = rl8.[rl_Indent6]
AND rl9.[rl_Indent5] = rl8.[rl_Indent5]
AND rl9.[rl_Indent4] = rl8.[rl_Indent4]
AND rl9.[rl_Indent3] = rl8.[rl_Indent3]
AND rl9.[rl_Indent2] = rl8.[rl_Indent2]
AND rl9.[rl_Indent1] = rl8.[rl_Indent1]
AND rl9.[rl_Indent9] <> 0
AND rl9.[rl_Indent10] = 0)
WHERE
rl0.[rl_CompanyID] = #CompanyID
AND rl0.[rl_Indent1] = 0);
INSERT INTO #tmp2([CompanyName],[rl_Index],[rl_Addr1],[rl_Addr2],[rl_DisplayName])
(SELECT DISTINCT
rl0.[rl_Name] AS [CompanyName]
,rl1.[rl_Index]
,rl1.[rl_Addr1]
,rl1.[rl_Addr2]
,CASE WHEN (rl1.[rl_indent1] <> 0 AND rl1.[rl_indent2] = 0 AND rl1.[rl_indent3] = 0 AND rl1.[rl_indent4] = 0 AND rl1.[rl_indent5] = 0 AND rl1.[rl_indent6] = 0 AND rl1.[rl_indent7] = 0 AND rl1.[rl_indent8] = 0 AND rl1.[rl_indent9] = 0) THEN rl1.[rl_Name] END AS [rl_DisplayName]
FROM
[dbo].[ReportingLevels] rl0
LEFT JOIN ReportingLevels rl1
ON (rl1.[rl_CompanyID] = #CompanyID
AND rl1.[rl_Indent1] <> 0
AND rl1.[rl_Indent2] = 0)
LEFT JOIN ReportingLevels rl2
ON (rl2.[rl_CompanyID] = #CompanyID
AND rl2.[rl_Indent1] = rl1.[rl_Indent1]
AND rl2.[rl_Indent2] <> 0
AND rl2.[rl_Indent3] = 0)
LEFT JOIN ReportingLevels rl3
ON (rl3.[rl_CompanyID] = #CompanyID
AND rl3.[rl_Indent2] = rl2.[rl_Indent2]
AND rl3.[rl_Indent1] = rl2.[rl_Indent1]
AND rl3.[rl_Indent3] <> 0
AND rl3.[rl_Indent4] = 0)
LEFT JOIN ReportingLevels rl4
ON (rl4.[rl_CompanyID] = #CompanyID
AND rl4.[rl_Indent3] = rl3.[rl_Indent3]
AND rl4.[rl_Indent2] = rl3.[rl_Indent2]
AND rl4.[rl_Indent1] = rl3.[rl_Indent1]
AND rl4.[rl_Indent4] <> 0
AND rl4.[rl_Indent5] = 0)
LEFT JOIN [ReportingLevels] rl5
ON (rl5.[rl_CompanyID] = #CompanyID
AND rl5.[rl_Indent4] = rl4.[rl_Indent4]
AND rl5.[rl_Indent3] = rl4.[rl_Indent3]
AND rl5.[rl_Indent2] = rl4.[rl_Indent2]
AND rl5.[rl_Indent1] = rl4.[rl_Indent1]
AND rl5.[rl_Indent5] <> 0
AND rl5.[rl_Indent6] = 0)
LEFT JOIN ReportingLevels rl6
ON (rl6.[rl_CompanyID] = #CompanyID
AND rl6.[rl_Indent5] = rl5.[rl_Indent5]
AND rl6.[rl_Indent4] = rl5.[rl_Indent4]
AND rl6.[rl_Indent3] = rl5.[rl_Indent3]
AND rl6.[rl_Indent2]= rl5.[rl_Indent2]
AND rl6.[rl_Indent1] = rl5.[rl_Indent1]
AND rl6.[rl_Indent6] <> 0
AND rl6.[rl_Indent7] = 0)
LEFT JOIN ReportingLevels rl7
ON (rl7.[rl_CompanyID] = #CompanyID
AND rl7.[rl_Indent6] = rl6.[rl_Indent6]
AND rl7.[rl_Indent5] = rl6.[rl_Indent5]
AND rl7.[rl_Indent4] = rl6.[rl_Indent4]
AND rl7.[rl_Indent3] = rl6.[rl_Indent3]
AND rl7.[rl_Indent2] = rl6.[rl_Indent2]
AND rl7.[rl_Indent1] = rl6.[rl_Indent1]
AND rl7.[rl_Indent7] <> 0
AND rl7.[rl_Indent8] = 0)
LEFT JOIN ReportingLevels rl8
ON (rl8.[rl_CompanyID] = #CompanyID
AND rl8.[rl_Indent7] = rl7.[rl_Indent7]
AND rl8.[rl_Indent6] = rl7.[rl_Indent6]
AND rl8.[rl_Indent5] = rl7.[rl_Indent5]
AND rl8.[rl_Indent4] = rl7.[rl_Indent4]
AND rl8.[rl_Indent3] = rl7.[rl_Indent3]
AND rl8.[rl_Indent2] = rl7.[rl_Indent2]
AND rl8.[rl_Indent1] = rl7.[rl_Indent1]
AND rl8.[rl_Indent8] <> 0
AND rl7.[rl_Indent9] = 0)
LEFT JOIN ReportingLevels rl9
ON (rl9.[rl_CompanyID] = #CompanyID
AND rl9.[rl_Indent8] = rl8.[rl_Indent8]
AND rl9.[rl_Indent7] = rl8.[rl_Indent7]
AND rl9.[rl_Indent6] = rl8.[rl_Indent6]
AND rl9.[rl_Indent5] = rl8.[rl_Indent5]
AND rl9.[rl_Indent4] = rl8.[rl_Indent4]
AND rl9.[rl_Indent3] = rl8.[rl_Indent3]
AND rl9.[rl_Indent2] = rl8.[rl_Indent2]
AND rl9.[rl_Indent1] = rl8.[rl_Indent1]
AND rl9.[rl_Indent9] <> 0
AND rl9.[rl_Indent10] = 0)
WHERE
rl0.[rl_CompanyID] = #CompanyID
AND rl0.[rl_Indent1] = 0);
INSERT INTO #result
SELECT * FROM #tmp1
UNION
SELECT * FROM #tmp2
ORDER BY [rl_DisplayName]
RETURN
END

You're trying to use the syntax for a inline table-valued function when you actually have a multi-statement table-valued function. See the full description here.
You're using this:
--Transact-SQL Inline Table-Valued Function Syntax
CREATE FUNCTION [ schema_name. ] function_name ( [ { #parameter_name [ AS ] [ type_schema_name. ] parameter_data_type
[ =default ] [ READONLY ] }
[ ,...n ]
]
)
RETURNS TABLE
[ WITH <function_option> [ ,...n ] ]
[ AS ]
RETURN [ ( ] select_stmt [ ) ]
[ ; ]
BUT, you really want this:
--Transact-SQL Multistatement Table-valued Function Syntax
CREATE FUNCTION [ schema_name. ] function_name ( [ { #parameter_name [ AS ] [ type_schema_name. ] parameter_data_type
[ =default ] [READONLY] }
[ ,...n ]
]
)
RETURNS #return_variable TABLE <table_type_definition>
[ WITH <function_option> [ ,...n ] ]
[ AS ]
BEGIN
function_body
RETURN
END
[ ; ]

To change function type you must have to drop function and then only you can change function type by creating new type function.
There are three types of functions.
Scalar
Inline table valued
Multi Statement
ALTER cannot be used to change the function type.
You need to DROP and CREATE the function

Your header syntax for inline table valued functions
...
RETURNS TABLE
AS
RETURN
(
SELECT .. FROM something WHERE ...
)
GO --end of function
You have a multi-valued table function.
...
RETURNS #result TABLE
(
CompanyName VARCHAR(300),
[rl_Index] INT,
[rl_Addr1] VARCHAR(MAX),
[rl_Addr2] VARCHAR(MAX),
[rl_DisplayName] VARCHAR(MAX)
);
AS
BEGIN
...
Do this
Do that
Data into #result
END --of function
GO
See MSDN for examples

Just Drop and Create your SQL statement

Related

Microsoft SQL query to view

I have this complex query that i want to turn into a view.
This query comes from https://snippets.cacher.io/snippet/3e84b01b7d52b4ca7807 and i want to save it in a view or even as a table if possible.
`
/*##=============================================*/
/*## QUERY BODY */
/*##=============================================*/
/* #region QueryBody */
/* Testing variables !! Need to be commented for Production !! */
-- DECLARE #UserSIDs AS NVARCHAR(10) = 'Disabled';
-- DECLARE #CollectionID AS NVARCHAR(10) = 'SMS00001';
-- DECLARE #Locale AS INT = 2;
-- DECLARE #Categories AS NVARCHAR(250) = 'Tools';
-- DECLARE #Compliant AS INT = 0;
-- DECLARE #Targeted AS INT = 1;
-- DECLARE #Superseded AS INT = 0;
-- DECLARE #ArticleID AS NVARCHAR(10) = '';
-- DECLARE #ExcludeArticleIDs AS NVARCHAR(250) = '';
/* Variable declaration */
DECLARE #LCID AS INT = dbo.fn_LShortNameToLCID(#Locale);
DECLARE #HelperFunctionExists AS INT = 0;
/* Perform cleanup */
IF OBJECT_ID('tempdb..#MaintenanceInfo', 'U') IS NOT NULL
DROP TABLE #MaintenanceInfo;
/* Check for helper function */
IF OBJECT_ID('[dbo].[ufn_CM_GetNextMaintenanceWindow]') IS NOT NULL
SET #HelperFunctionExists = 1;
/* Initialize HealthState descriptor table */
DECLARE #HealthState TABLE (
BitMask INT
, StateName NVARCHAR(250)
)
/* Populate HealthState table */
INSERT INTO #HealthState (BitMask, StateName)
VALUES
('0', 'Healthy')
, ('1', 'Unmanaged')
, ('2', 'Inactive')
, ('4', 'Health Evaluation Failed')
, ('8', 'Pending Restart')
, ('16', 'Update Scan Failed')
, ('32', 'Update Scan Late')
, ('64', 'No Maintenance Window')
, ('128', 'Distant Maintenance Window')
, ('256', 'Expired Maintenance Window')
/* Initialize ClientState descriptor table */
DECLARE #ClientState TABLE (
BitMask INT
, StateName NVARCHAR(100)
)
/* Populate ClientState table */
INSERT INTO #ClientState (BitMask, StateName)
VALUES
('0', 'No Reboot')
, ('1', 'Configuration Manager')
, ('2', 'File Rename')
, ('4', 'Windows Update')
, ('8', 'Add or Remove Feature')
CREATE TABLE #MaintenanceInfo (
ResourceID INT
, NextServiceWindow DATETIME
)
/* Get maintenance data */
IF #HelperFunctionExists = 1
BEGIN
WITH Maintenance_CTE AS (
SELECT
CollectionMembers.ResourceID
, NextServiceWindow.Duration
, NextServiceWindow.NextServiceWindow
, RowNumber = DENSE_RANK() OVER (PARTITION BY ResourceID ORDER BY NextServiceWindow.NextServiceWindow)
, ServiceWindowType
, ServiceWindow.Enabled
FROM vSMS_ServiceWindow AS ServiceWindow
JOIN fn_rbac_FullCollectionMembership(#UserSIDs) AS CollectionMembers ON CollectionMembers.CollectionID = ServiceWindow.SiteID
JOIN fn_rbac_Collection(#UserSIDs) AS Collections ON Collections.CollectionID = CollectionMembers.CollectionID
AND Collections.CollectionType = 2 -- Device Collections
CROSS APPLY ufn_CM_GetNextMaintenanceWindow(ServiceWindow.Schedules, ServiceWindow.RecurrenceType) AS NextServiceWindow
WHERE NextServiceWindow.NextServiceWindow IS NOT NULL
AND ServiceWindowType <> 5 -- OSD Service
)
/* Populate MaintenanceInfo table and remove duplicates */
INSERT INTO #MaintenanceInfo(ResourceID, NextServiceWindow)
SELECT
ResourceID
, NextServiceWindow
FROM Maintenance_CTE
WHERE RowNumber = 1
END
/* Get update data */
;
WITH UpdateInfo_CTE
AS (
SELECT
ResourceID = Systems.ResourceID
, Missing = COUNT(*)
FROM fn_rbac_R_System(#UserSIDs) AS Systems
JOIN fn_rbac_UpdateComplianceStatus(#UserSIDs) AS ComplianceStatus ON ComplianceStatus.ResourceID = Systems.ResourceID
AND ComplianceStatus.Status = 2 -- Filter on 'Required' (0 = Unknown, 1 = NotRequired, 2 = Required, 3 = Installed)
JOIN fn_rbac_ClientCollectionMembers(#UserSIDs) AS CollectionMembers ON CollectionMembers.ResourceID = ComplianceStatus.ResourceID
JOIN fn_rbac_UpdateInfo(#LCID, #UserSIDs) AS UpdateCIs ON UpdateCIs.CI_ID = ComplianceStatus.CI_ID
AND UpdateCIs.IsSuperseded IN (#Superseded)
AND UpdateCIs.CIType_ID IN (1, 8) -- Filter on 1 Software Updates, 8 Software Update Bundle (v_CITypes)
AND UpdateCIs.ArticleID NOT IN ( -- Filter on ArticleID csv list
SELECT VALUE FROM STRING_SPLIT(#ExcludeArticleIDs, ',')
)
AND UpdateCIs.Title NOT LIKE ( -- Filter Preview updates
'[1-9][0-9][0-9][0-9]-[0-9][0-9]_Preview_of_%'
)
JOIN fn_rbac_CICategoryInfo_All(#LCID, #UserSIDs) AS CICategory ON CICategory.CI_ID = ComplianceStatus.CI_ID
AND CICategory.CategoryTypeName = 'UpdateClassification'
AND CICategory.CategoryInstanceName IN (#Categories) -- Filter on Selected Update Classification Categories
LEFT JOIN fn_rbac_CITargetedMachines(#UserSIDs) AS Targeted ON Targeted.ResourceID = ComplianceStatus.ResourceID
AND Targeted.CI_ID = ComplianceStatus.CI_ID
WHERE CollectionMembers.CollectionID = #CollectionID
AND IIF(Targeted.ResourceID IS NULL, 0, 1) IN (#Targeted) -- Filter on 'Targeted' or 'NotTargeted'
AND IIF(UpdateCIs.ArticleID = #ArticleID, 1, 0) = IIF(#ArticleID <> '', 1, 0)
GROUP BY
Systems.ResourceID
)
/* Get device info */
SELECT
Systems.ResourceID
/* Set Health states. You can find the coresponding values in the HealthState table above */
, HealthStates = (
IIF(CombinedResources.IsClient != 1, POWER(1, 1), 0)
+
IIF(
ClientSummary.ClientStateDescription = 'Inactive/Pass'
OR
ClientSummary.ClientStateDescription = 'Inactive/Fail'
OR
ClientSummary.ClientStateDescription = 'Inactive/Unknown'
, POWER(2, 1), 0)
+
IIF(
ClientSummary.ClientStateDescription = 'Active/Fail'
OR
ClientSummary.ClientStateDescription = 'Inactive/Fail'
, POWER(4, 1), 0
)
+
IIF(CombinedResources.ClientState != 0, POWER(8, 1), 0)
+
IIF(UpdateScan.LastErrorCode != 0, POWER(16, 1), 0)
+
IIF(UpdateScan.LastScanTime < (SELECT DATEADD(dd, -14, CURRENT_TIMESTAMP)), POWER(32, 1), 0)
+
IIF(ISNULL(NextServiceWindow, 0) = 0 AND #HelperFunctionExists = 1, POWER(64, 1), 0)
+
IIF(NextServiceWindow > (SELECT DATEADD(dd, 30, CURRENT_TIMESTAMP)), POWER(128, 1), 0)
+
IIF(NextServiceWindow < (CURRENT_TIMESTAMP), POWER(256, 1), 0)
)
, Missing = ISNULL(Missing, (IIF(CombinedResources.IsClient = 1, 0, NULL)))
, Device = (
IIF(
SystemNames.Resource_Names0 IS NOT NULL, UPPER(SystemNames.Resource_Names0)
, IIF(Systems.Full_Domain_Name0 IS NOT NULL, Systems.Name0 + '.' + Systems.Full_Domain_Name0, Systems.Name0)
)
)
, OperatingSystem = (
CASE
WHEN OperatingSystem.Caption0 != '' THEN
CONCAT(
REPLACE(OperatingSystem.Caption0, 'Microsoft ', ''), -- Remove 'Microsoft ' from OperatingSystem
REPLACE(OperatingSystem.CSDVersion0, 'Service Pack ', ' SP') -- Replace 'Service Pack ' with ' SP' in OperatingSystem
)
ELSE (
/* Workaround for systems not in GS_OPERATING_SYSTEM table */
CASE
WHEN CombinedResources.DeviceOS LIKE '%Workstation 6.1%' THEN 'Windows 7'
WHEN CombinedResources.DeviceOS LIKE '%Workstation 6.2%' THEN 'Windows 8'
WHEN CombinedResources.DeviceOS LIKE '%Workstation 6.3%' THEN 'Windows 8.1'
WHEN CombinedResources.DeviceOS LIKE '%Workstation 10.0%' THEN 'Windows 10'
WHEN CombinedResources.DeviceOS LIKE '%Server 6.0' THEN 'Windows Server 2008'
WHEN CombinedResources.DeviceOS LIKE '%Server 6.1' THEN 'Windows Server 2008R2'
WHEN CombinedResources.DeviceOS LIKE '%Server 6.2' THEN 'Windows Server 2012'
WHEN CombinedResources.DeviceOS LIKE '%Server 6.3' THEN 'Windows Server 2012 R2'
WHEN Systems.Operating_System_Name_And0 LIKE '%Server 10%' THEN (
CASE
WHEN CAST(REPLACE(Build01, '.', '') AS INTEGER) > 10017763 THEN 'Windows Server 2019'
ELSE 'Windows Server 2016'
END
)
ELSE Systems.Operating_System_Name_And0
END
)
END
)
, LastBootTime = (
CONVERT(NVARCHAR(16), OperatingSystem.LastBootUpTime0, 120)
)
, PendingRestart = (
CASE
WHEN CombinedResources.IsClient = 0
OR CombinedResources.ClientState = 0
THEN NULL
ELSE (
STUFF(
REPLACE(
(
SELECT '#!' + LTRIM(RTRIM(StateName)) AS [data()]
FROM #ClientState
WHERE BitMask & CombinedResources.ClientState <> 0
FOR XML PATH('')
),
' #!',', '
),
1, 2, ''
)
)
END
)
, ClientState = (
CASE CombinedResources.IsClient
WHEN 1 THEN ClientSummary.ClientStateDescription
ELSE 'Unmanaged'
END
)
, ClientVersion = CombinedResources.ClientVersion
, LastUpdateScan = (
CONVERT(NVARCHAR(16), UpdateScan.LastScanTime, 120)
)
, LastScanLocation = NULLIF(UpdateScan.LastScanPackageLocation, '')
, LastScanError = NULLIF(UpdateScan.LastErrorCode, 0)
, NextServiceWindow = IIF(CombinedResources.IsClient != 1, NULL, CONVERT(NVARCHAR(16), NextServiceWindow, 120))
FROM fn_rbac_R_System(#UserSIDs) AS Systems
JOIN fn_rbac_CombinedDeviceResources(#UserSIDs) AS CombinedResources ON CombinedResources.MachineID = Systems.ResourceID
LEFT JOIN fn_rbac_RA_System_ResourceNames(#UserSIDs) AS SystemNames ON SystemNames.ResourceID = Systems.ResourceID
LEFT JOIN fn_rbac_GS_OPERATING_SYSTEM(#UserSIDs) AS OperatingSystem ON OperatingSystem.ResourceID = Systems.ResourceID
LEFT JOIN fn_rbac_CH_ClientSummary(#UserSIDs) AS ClientSummary ON ClientSummary.ResourceID = Systems.ResourceID
LEFT JOIN fn_rbac_UpdateScanStatus(#UserSIDs) AS UpdateScan ON UpdateScan.ResourceID = Systems.ResourceID
LEFT JOIN #MaintenanceInfo AS Maintenance ON Maintenance.ResourceID = Systems.ResourceID
LEFT JOIN UpdateInfo_CTE AS UpdateInfo ON UpdateInfo.ResourceID = Systems.ResourceID
JOIN fn_rbac_FullCollectionMembership(#UserSIDs) AS CollectionMembers ON CollectionMembers.ResourceID = Systems.ResourceID
WHERE CollectionMembers.CollectionID = #CollectionID
AND (
CASE -- Compliant (0 = No, 1 = Yes, 2 = Unknown)
WHEN Missing = 0 OR (Missing IS NULL AND Systems.Client0 = 1) THEN 1 -- Yes
WHEN Missing > 0 AND Missing IS NOT NULL THEN 0 -- No
ELSE 2 -- Unknown
END
) IN (#Compliant)
/* Perform cleanup */
IF OBJECT_ID('tempdb..#MaintenanceInfo', 'U') IS NOT NULL
DROP TABLE #MaintenanceInfo;
/* #endregion */
/*##=============================================*/
/*## END QUERY BODY */
/*##=============================================*/
`
Is there an easy way to achieve this?
I have tried to look at the official Microsoft documentation but are still not able to convert the query to a view. https://learn.microsoft.com/en-us/sql/t-sql/statements/create-view-transact-sql?view=sql-server-ver16
As I am new to SQL language I am not sure where to start.
So I agree with Larnu, that this probably doesn't make a ton of sense. But there are cases where one might want to be able to run multiple batches of queries / procedural code from an object that's as consumable as a view. I've done this once in a case where I needed to maximize my options for performance tuning without losing the consumability of the object. So for the sake of when it does make sense, this is something you could do:
Wrap your code in a stored procedure.
Use OPENQUERY() to call your procedure.
Wrap the OPENQUERY() call in a view.
Limitations with this methodology is it's rather static:
You can't pass parameters to your stored procedure
If you use temp tables in your stored procedure, then you need to use the WITH RESULT SETS clause to explicitly define the shape of your result set
The procedure can only return one result set
The SQL Server Engine puts a hard-coded cardinality estimate of 10,000 against OPENQUERY(). So in cases where your procedure returns a lot more rows (typically an order of magnitude or more) than 10,000, e.g. 1 million rows, then you may experience some performance issues with joining the wrapper view to other objects.
Example:
-- Step 1: Wrap the procedural code in a stored procedure
CREATE PROCEDURE dbo.RunSomeCode
AS
BEGIN
CREATE TABLE #Results (ID INT, SomeValue VARCHAR(100));
DECLARE #SomeVariable INT = 0;
WHILE (#SomeVariable < 5)
BEGIN
SET #SomeVariable = #SomeVariable + 1;
INSERT INTO #Results (ID, SomeValue)
SELECT ID, SomeValue
FROM SomeTable
WHERE ID = #SomeVariable
END
SELECT ID, SomeValue
FROM #Results;
END
GO
-- Step 2 & 3: Wrap an OPENQUERY() call to the procedure in a view.
CREATE VIEW dbo.SomeView
AS
SELECT ID, SomeValue
FROM OPENQUERY
(
'
LocalServerName,
EXEC dbo.RunSomeCode
WITH RESULT SETS
((
ID INT,
SomeValue VARCHAR(100)
))
'
);
Voila, you can now execute the procedure by SELECTing from the view:
SELECT ID, SomeValue
FROM dbo.SomeView;

Stored procedue issue with AND statement when checking is null

I can't work out why my value is being ignored.
In my stored procedure it has these two AND statements
AND (#Current IS NULL OR (o.[OrderStatusId] <> 40) AND (o.[OrderStatusId] <> 30) AND ( NOT ((o.[ShippingStatusId] IN (30, 40)) AND (o.[PaymentStatusId] IN (30, 35, 40)))))
AND (#Printed IS NULL OR o.[Printed] = #Printed)
The #Printed value is a bit same as #Current, and is passed through to the stored procedure just the same as #Current
But the printed value doesn't pull results, it's like it's doing nothing although I know the results should vary.
I'm converting a linq query to the stored procedure, so I know the results should differ.
Here is the part of the linq query which is used.
if (current.HasValue && current.Value)
query = query.Where(o => o.OrderStatusId != (int)OrderStatus.Cancelled && o.OrderStatusId != (int)OrderStatus.Complete && !((o.ShippingStatusId == (int)ShippingStatus.Shipped || o.ShippingStatusId == (int)ShippingStatus.Delivered) && o.Printed && (o.PaymentStatusId == (int)PaymentStatus.Paid || o.PaymentStatusId == (int)PaymentStatus.PartiallyRefunded || o.PaymentStatusId == (int)PaymentStatus.Refunded)));
if (printed.HasValue)
query = query.Where(o => printed.Value == o.Printed);
Any ideas
UPDATE:
Looking at the query from linq in vs debugger I can see the following query, but I' no db expert so I'm a little lost looking at this one.
{SELECT
[Project2].[Id] AS [Id],
[Project2].[OrderGuid] AS [OrderGuid],
[Project2].[StoreId] AS [StoreId],
[Project2].[CustomerId] AS [CustomerId],
[Project2].[BillingAddressId] AS [BillingAddressId],
[Project2].[ShippingAddressId] AS [ShippingAddressId],
[Project2].[PickUpInStore] AS [PickUpInStore],
[Project2].[OrderStatusId] AS [OrderStatusId],
[Project2].[ShippingStatusId] AS [ShippingStatusId],
[Project2].[PaymentStatusId] AS [PaymentStatusId],
[Project2].[PaymentMethodSystemName] AS [PaymentMethodSystemName],
[Project2].[CustomerCurrencyCode] AS [CustomerCurrencyCode],
[Project2].[CurrencyRate] AS [CurrencyRate],
[Project2].[CustomerTaxDisplayTypeId] AS [CustomerTaxDisplayTypeId],
[Project2].[VatNumber] AS [VatNumber],
[Project2].[OrderSubtotalInclTax] AS [OrderSubtotalInclTax],
[Project2].[OrderSubtotalExclTax] AS [OrderSubtotalExclTax],
[Project2].[OrderSubTotalDiscountInclTax] AS [OrderSubTotalDiscountInclTax],
[Project2].[OrderSubTotalDiscountExclTax] AS [OrderSubTotalDiscountExclTax],
[Project2].[OrderShippingInclTax] AS [OrderShippingInclTax],
[Project2].[OrderShippingExclTax] AS [OrderShippingExclTax],
[Project2].[PaymentMethodAdditionalFeeInclTax] AS [PaymentMethodAdditionalFeeInclTax],
[Project2].[PaymentMethodAdditionalFeeExclTax] AS [PaymentMethodAdditionalFeeExclTax],
[Project2].[TaxRates] AS [TaxRates],
[Project2].[OrderTax] AS [OrderTax],
[Project2].[OrderDiscount] AS [OrderDiscount],
[Project2].[OrderTotal] AS [OrderTotal],
[Project2].[RefundedAmount] AS [RefundedAmount],
[Project2].[RewardPointsWereAdded] AS [RewardPointsWereAdded],
[Project2].[CheckoutAttributeDescription] AS [CheckoutAttributeDescription],
[Project2].[CheckoutAttributesXml] AS [CheckoutAttributesXml],
[Project2].[CustomerLanguageId] AS [CustomerLanguageId],
[Project2].[AffiliateId] AS [AffiliateId],
[Project2].[CustomerIp] AS [CustomerIp],
[Project2].[AllowStoringCreditCardNumber] AS [AllowStoringCreditCardNumber],
[Project2].[CardType] AS [CardType],
[Project2].[CardName] AS [CardName],
[Project2].[CardNumber] AS [CardNumber],
[Project2].[MaskedCreditCardNumber] AS [MaskedCreditCardNumber],
[Project2].[CardCvv2] AS [CardCvv2],
[Project2].[CardExpirationMonth] AS [CardExpirationMonth],
[Project2].[CardExpirationYear] AS [CardExpirationYear],
[Project2].[AuthorizationTransactionId] AS [AuthorizationTransactionId],
[Project2].[AuthorizationTransactionCode] AS [AuthorizationTransactionCode],
[Project2].[AuthorizationTransactionResult] AS [AuthorizationTransactionResult],
[Project2].[CaptureTransactionId] AS [CaptureTransactionId],
[Project2].[CaptureTransactionResult] AS [CaptureTransactionResult],
[Project2].[SubscriptionTransactionId] AS [SubscriptionTransactionId],
[Project2].[PaidDateUtc] AS [PaidDateUtc],
[Project2].[ShippingMethod] AS [ShippingMethod],
[Project2].[Printed] AS [Printed],
[Project2].[PrintedOnUtc] AS [PrintedOnUtc],
[Project2].[IsSupport] AS [IsSupport],
[Project2].[EditedStatusId] AS [EditedStatusId],
[Project2].[Deleted] AS [Deleted],
[Project2].[Id1] AS [Id1]
FROM ( SELECT
CASE WHEN (([Extent1].[Printed] <> 1) AND (N'Express Delivery' = [Extent1].[ShippingMethod])) THEN N'1' ELSE N'0' END AS [C1],
CASE WHEN ([Extent1].[Printed] <> 1) THEN CASE WHEN (([Extent1].[ShippingMethod] IN (N'Fast Delivery',N'My Point Pickup')) AND ( NOT EXISTS (SELECT
1 AS [C1]
FROM [dbo].[GenericAttribute] AS [Extent3]
WHERE (N'WarehouseOverride' = [Extent3].[Key]) AND (N'Order' = [Extent3].[KeyGroup]) AND ([Extent3].[EntityId] = [Extent1].[Id])
))) THEN N'0' ELSE N'1' END ELSE N'0' END AS [C2],
[Extent1].[Id] AS [Id],
[Extent1].[OrderGuid] AS [OrderGuid],
[Extent1].[StoreId] AS [StoreId],
[Extent1].[CustomerId] AS [CustomerId],
[Extent1].[BillingAddressId] AS [BillingAddressId],
[Extent1].[ShippingAddressId] AS [ShippingAddressId],
[Extent1].[PickUpInStore] AS [PickUpInStore],
[Extent1].[OrderStatusId] AS [OrderStatusId],
[Extent1].[ShippingStatusId] AS [ShippingStatusId],
[Extent1].[PaymentStatusId] AS [PaymentStatusId],
[Extent1].[PaymentMethodSystemName] AS [PaymentMethodSystemName],
[Extent1].[CustomerCurrencyCode] AS [CustomerCurrencyCode],
[Extent1].[CurrencyRate] AS [CurrencyRate],
[Extent1].[CustomerTaxDisplayTypeId] AS [CustomerTaxDisplayTypeId],
[Extent1].[VatNumber] AS [VatNumber],
[Extent1].[OrderSubtotalInclTax] AS [OrderSubtotalInclTax],
[Extent1].[OrderSubtotalExclTax] AS [OrderSubtotalExclTax],
[Extent1].[OrderSubTotalDiscountInclTax] AS [OrderSubTotalDiscountInclTax],
[Extent1].[OrderSubTotalDiscountExclTax] AS [OrderSubTotalDiscountExclTax],
[Extent1].[OrderShippingInclTax] AS [OrderShippingInclTax],
[Extent1].[OrderShippingExclTax] AS [OrderShippingExclTax],
[Extent1].[PaymentMethodAdditionalFeeInclTax] AS [PaymentMethodAdditionalFeeInclTax],
[Extent1].[PaymentMethodAdditionalFeeExclTax] AS [PaymentMethodAdditionalFeeExclTax],
[Extent1].[TaxRates] AS [TaxRates],
[Extent1].[OrderTax] AS [OrderTax],
[Extent1].[OrderDiscount] AS [OrderDiscount],
[Extent1].[OrderTotal] AS [OrderTotal],
[Extent1].[RefundedAmount] AS [RefundedAmount],
[Extent1].[RewardPointsWereAdded] AS [RewardPointsWereAdded],
[Extent1].[CheckoutAttributeDescription] AS [CheckoutAttributeDescription],
[Extent1].[CheckoutAttributesXml] AS [CheckoutAttributesXml],
[Extent1].[CustomerLanguageId] AS [CustomerLanguageId],
[Extent1].[AffiliateId] AS [AffiliateId],
[Extent1].[CustomerIp] AS [CustomerIp],
[Extent1].[AllowStoringCreditCardNumber] AS [AllowStoringCreditCardNumber],
[Extent1].[CardType] AS [CardType],
[Extent1].[CardName] AS [CardName],
[Extent1].[CardNumber] AS [CardNumber],
[Extent1].[MaskedCreditCardNumber] AS [MaskedCreditCardNumber],
[Extent1].[CardCvv2] AS [CardCvv2],
[Extent1].[CardExpirationMonth] AS [CardExpirationMonth],
[Extent1].[CardExpirationYear] AS [CardExpirationYear],
[Extent1].[AuthorizationTransactionId] AS [AuthorizationTransactionId],
[Extent1].[AuthorizationTransactionCode] AS [AuthorizationTransactionCode],
[Extent1].[AuthorizationTransactionResult] AS [AuthorizationTransactionResult],
[Extent1].[CaptureTransactionId] AS [CaptureTransactionId],
[Extent1].[CaptureTransactionResult] AS [CaptureTransactionResult],
[Extent1].[SubscriptionTransactionId] AS [SubscriptionTransactionId],
[Extent1].[PaidDateUtc] AS [PaidDateUtc],
[Extent1].[ShippingMethod] AS [ShippingMethod],
[Extent1].[Printed] AS [Printed],
[Extent1].[PrintedOnUtc] AS [PrintedOnUtc],
[Extent1].[IsSupport] AS [IsSupport],
[Extent1].[EditedStatusId] AS [EditedStatusId],
[Extent1].[Deleted] AS [Deleted],
[Extent2].[Id] AS [Id1]
FROM [dbo].[Order] AS [Extent1]
LEFT OUTER JOIN [dbo].[RewardPointsHistory] AS [Extent2] ON ([Extent2].[UsedWithOrder_Id] IS NOT NULL) AND ([Extent1].[Id] = [Extent2].[UsedWithOrder_Id])
WHERE ([Extent1].[Deleted] <> 1) AND (40 <> [Extent1].[OrderStatusId]) AND (30 <> [Extent1].[OrderStatusId]) AND ( NOT (([Extent1].[ShippingStatusId] IN (30,40)) AND ([Extent1].[Printed] = 1) AND ([Extent1].[PaymentStatusId] IN (30,35,40))))
) AS [Project2]
ORDER BY [Project2].[C1] DESC, [Project2].[Printed] ASC, [Project2].[C2] DESC, [Project2].[CreatedOnUtc] DESC}
Here is my stored procedure for you to look at:
USE [Test]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[OrderLoad]
-- Add the parameters for the stored procedure here
#OrderId int = null,
#CustomerId int = null,
#WarehouseId int = null,
#BillingCountryId int = null,
#PaymentMethodSystemName nvarchar(max) = null,
#OrderStatusId int = null,
#PaymentStatusId int = null,
#ShippingStatusId int = null,
#BillingEmail nvarchar(max) = null,
#BillingFirstName nvarchar(max) = null,
#BillingLastName nvarchar(max) = null,
#PurchasedPreviously bit = null,
#Printed bit = null,
#OrderNotes nvarchar(max) = null,
#ZendeskId nvarchar(max) = null,
#RexCode nvarchar(max) = null,
#Current bit = null,
#Challenge bit = null,
#ShippingMethod nvarchar(max) = null,
#EditedStatus int = null,
#OrderGuid nvarchar(max) = null,
#SupportReason int = null,
#CreatedFromUtc datetime = null,
#CreatedToUtc datetime = null,
#IsSupport bit = null,
#PageIndex int = 0,
#PageSize int = 2147483644,
#TotalRecords int = null OUTPUT
AS
BEGIN
DECLARE
#sql nvarchar(max)
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
create table #TempTotal (RowNum int identity(1,1), id int);
--select all
INSERT INTO #TempTotal ([id])
SELECT o.[Id]
FROM [Test].[dbo].[Order] o with (NOLOCK)
-- Another alternative to bypass left join, which works with pagination
LEFT join [Test].[dbo].[Address] a on a.Id = o.BillingAddressId and (
coalesce(#BillingEmail,'') <> ''
or coalesce(#BillingFirstName,'') <> ''
or coalesce(#BillingLastName,'') <> ''
or coalesce(#BillingCountryId,'') <> ''
)
WHERE
o.[Deleted] = 0
/*AND (#BillingEmail IS null OR a.[Email] LIKE '%' + #BillingEmail + '%')
AND (#BillingFirstName IS null OR a.[FirstName] LIKE '%' + #BillingFirstName + '%')
AND (#BillingLastName IS null OR a.[LastName] LIKE '%' + #BillingLastName + '%')
AND (#BillingCountryId IS null OR a.[CountryId] = #BillingCountryId)
*/
AND (#Printed IS NULL OR o.[Printed] = #Printed)
AND (#Current IS NULL OR (o.[OrderStatusId] <> 40) AND (o.[OrderStatusId] <> 30) AND ( NOT ((o.[ShippingStatusId] IN (30, 40)) /*AND (o.[Printed] = '1')*/ AND (o.[PaymentStatusId] IN (30, 35, 40)))))
AND (#IsSupport IS null OR o.[IsSupport] = #IsSupport)
--paging
DECLARE #PageLowerBound int
SET #PageLowerBound = #PageSize * #PageIndex
-- Return the paged records
select [Id] --note select * can produce unexpected results
,[OrderGuid]
,[RexOrderId]
,[StoreId]
,[CustomerId]
,[BillingAddressId]
,[ShippingAddressId]
,[PickUpInStore]
,[OrderStatusId]
,[ShippingStatusId]
,[PaymentStatusId]
,[PaymentMethodSystemName]
,[CustomerCurrencyCode]
,[CurrencyRate]
,[CustomerTaxDisplayTypeId]
,[VatNumber]
,[OrderSubtotalInclTax]
,[OrderSubtotalExclTax]
,[OrderSubTotalDiscountInclTax]
,[OrderSubTotalDiscountExclTax]
,[OrderShippingInclTax]
,[OrderShippingExclTax]
,[PaymentMethodAdditionalFeeInclTax]
,[PaymentMethodAdditionalFeeExclTax]
,[TaxRates]
,[OrderTax]
,[OrderDiscount]
,[OrderTotal]
,[RefundedAmount]
,[RewardPointsWereAdded]
,[CheckoutAttributeDescription]
,[CheckoutAttributesXml]
,[CustomerLanguageId]
,[AffiliateId]
,[CustomerIp]
,[AllowStoringCreditCardNumber]
,[CardType]
,[CardName]
,[CardNumber]
,[MaskedCreditCardNumber]
,[CardCvv2]
,[CardExpirationMonth]
,[CardExpirationYear]
,[AuthorizationTransactionId]
,[AuthorizationTransactionCode]
,[AuthorizationTransactionResult]
,[CaptureTransactionId]
,[CaptureTransactionResult]
,[SubscriptionTransactionId]
,[PaidDateUtc]
,[ShippingMethod]
,[Printed]
,[Deleted]
,[CreatedOnUtc]
,[EditedStatusId]
,[IsSupport]
,[PrintedOnUtc]
from [Test].[dbo].[Order] ord with (NOLOCK)
where ord.[Id] in (
select id
from #TempTotal tt
)
ORDER BY
(CASE #IsSupport
WHEN 0 THEN ord.[Printed]
END) ASC
, (CASE #IsSupport
WHEN 0 THEN ord.[CreatedOnUtc]
END) DESC
, (CASE #IsSupport
WHEN 1 THEN ord.[CreatedOnUtc]
END) DESC
--ORDER BY ord.[CreatedOnUtc] DESC
OFFSET #PageLowerBound ROWS FETCH NEXT #PageSize ROWS ONLY;
--total records
select #TotalRecords = count(*) from #TempTotal;
DROP TABLE #TempTotal
END

Incorrect syntax near the keyword 'FOR' XML

I get the error
Incorrect syntax near the keyword 'FOR'
when I write '+# SirketNo+' to the dot.
I could not find the error.
Error :
Msg 156, Level 15, State 1, Line 110
Incorrect syntax near the keyword 'FOR'
Msg 102, Level 15, State 1, Line 125
Incorrect syntax near ','
Msg 102, Level 15, State 1, Line 137
Incorrect syntax near ','
My code:
DECLARE #SirketNo AS NVARCHAR(3)= '427',
#AliciAdreslerinDepartmani AS NVARCHAR(MAX) = 'MuhasebeMuduru',
#BilgiAliciAdreslerinDepartmani AS NVARCHAR(MAX) = 'Mudur',
#GizliAliciAdreslerinDepartmani AS NVARCHAR(MAX) = 'FinansKoordinatoru'', ''FinansSorumlusu'', ''Developer';
DECLARE #SqlQuery AS NVARCHAR(max) = N'
BEGIN
DECLARE #KacGunOnce INT= 13, #xml NVARCHAR(MAX), #KasaBakiye NVARCHAR(MAX), #AliciAdresler VARCHAR(MAX), #BilgiAliciAdresler VARCHAR(MAX), #GizliBilgiAliciAdresler VARCHAR(MAX), #vucut NVARCHAR(MAX), #Baslik VARCHAR(100)= '''', #CreatedBy VARCHAR(100)= '''', #Mesaj VARCHAR(250)= '''', #IsYeriNo SMALLINT;
DECLARE #mad TABLE
(logicalref INT IDENTITY(1, 1),
IsYeriNo SMALLINT,
KasaKodu VARCHAR(17),
KasaAdi VARCHAR(51),
AlıcıAdresler NVARCHAR(MAX),
BilgiAlıcıAdresler NVARCHAR(MAX),
GizliBilgiAlıcıAdresler NVARCHAR(MAX)
);
END; --Değişkenleri ve değişken tabloyu oluştur
BEGIN
INSERT INTO #mad
(IsYeriNo,
KasaKodu,
KasaAdi
)
SELECT DISTINCT
ksl.BRANCH,
lk.CODE,
lk.NAME
FROM LG_'+#SirketNo+'_01_KSLINES AS KSL WITH (NOLOCK)
JOIN L_CAPIUSER AS U WITH (NOLOCK) ON U.NR LIKE KSL.CAPIBLOCK_CREATEDBY
JOIN LG_'+#SirketNo+'_KSCARD AS lk ON lk.LOGICALREF = ksl.CARDREF
WHERE ksl.SIGN = 1
AND ksl.AMOUNT >= 300
AND CONVERT(VARCHAR(10), ksl.DATE_, 104) = CONVERT(VARCHAR(10), GETDATE() - #KacGunOnce, 104);
END; --Değişken tabloya verileri insert et
BEGIN
--Döngü için değişken atamaları
DECLARE #s INT= 1, #d INT=
(
SELECT COUNT(logicalref)
FROM #mad
);
--Döngü
WHILE #d >= #s
BEGIN
/**** DÖNGÜ BAŞLANGIÇ ****/
BEGIN
SELECT #KasaBakiye =
(
SELECT KasaKodu
FROM #mad
WHERE logicalref = #s
)+'' kodlu kasanın güncel bakiyesi: ''+FORMAT(SUM(CASHTOT.DEBIT - CASHTOT.CREDIT), ''c2'', ''tr-TR'')
FROM LG_'+#SirketNo+'_KSCARD AS CASHC WITH (NOLOCK),
LG_'+#SirketNo+'_01_CSHTOTS AS CASHTOT WITH (NOLOCK)
WHERE CASHC.CODE LIKE
(
SELECT KasaKodu
FROM #mad
WHERE logicalref = #s
)
AND CASHTOT.CARDREF = CASHC.LOGICALREF
AND CASHTOT.TOTTYPE = 1
AND CASHTOT.DAY_ >= 0
AND CASHTOT.DAY_ <= 365;
END; --Kasa Bakiyesini değişkene ata
BEGIN
-- İş yerini değişkene ata
SELECT #IsYeriNo = IsYeriNo
FROM #mad
WHERE logicalref = #s;
END; -- İş yerini değişkene ata;
BEGIN --Kasa hareketlerini HTML formatında XMLe dönüştür
SET #xml = CAST(
(
SELECT f.DATE_ AS ''td'',
'''',
f.FICHENO AS ''td'',
'''',
f.TRCODE AS ''td'',
'''',
f.CUSTTITLE AS ''td'',
'''',
f.LINEEXP AS ''td'',
'''',
f.AMOUNT AS ''td'',
'''',
f.REPORTRATE AS ''td'',
'''',
f.REPORTNET AS ''td'',
'''',
f.SPECODE AS ''td'',
'''',
f.CYPHCODE AS ''td'',
'''',
f.BRANCH AS ''td'',
'''',
f.NAME AS ''td'',
''''
FROM
(
SELECT ksl.DATE_,
KSL.FICHENO,
CASE TRCODE
WHEN 11
THEN ''CARİ HESAP TAHSİLAT''
WHEN 12
THEN ''CARİ İŞLEM''
WHEN 21
THEN ''BANKA İŞLEMİ''
WHEN 22
THEN ''BANKA İŞLEMİ''
WHEN 31
THEN ''FATURA İŞLEMİ''
WHEN 32
THEN ''FATURA İŞLEMİ''
WHEN 33
THEN ''FATURA İŞLEMİ''
WHEN 34
THEN ''FATURA İŞLEMİ''
WHEN 35
THEN ''FATURA İŞLEMİ''
WHEN 36
THEN ''FATURA İŞLEMİ''
WHEN 37
THEN ''FATURA İŞLEMİ''
WHEN 38
THEN ''FATURA İŞLEMİ''
WHEN 39
THEN ''FATURA İŞLEMİ''
WHEN 61
THEN ''ÇEK-SENET İŞLEMİ''
WHEN 62
THEN ''ÇEK-SENET İŞLEMİ''
WHEN 63
THEN ''ÇEK-SENET İŞLEMİ''
WHEN 64
THEN ''ÇEK-SENET İŞLEMİ''
WHEN 71
THEN ''KASA İŞLEMİ''
WHEN 72
THEN ''KASA İŞLEMİ''
WHEN 73
THEN ''KASA İŞLEMİ''
WHEN 74
THEN ''KASA İŞLEMİ''
ELSE ''TANIMSIZ İŞLEM''
END AS ''TRCODE'',
KSL.CUSTTITLE,
KSL.LINEEXP,
FORMAT(AMOUNT, ''c2'', ''tr-TR'') AS ''AMOUNT'',
CAST(REPORTRATE AS MONEY) AS ''REPORTRATE'',
CAST(REPORTNET AS MONEY) AS ''REPORTNET'',
KSL.SPECODE,
KSL.CYPHCODE,
KSL.BRANCH,
U.NAME
FROM LG_'+#SirketNo+'_01_KSLINES AS KSL WITH (NOLOCK) /**************************************/
JOIN L_CAPIUSER AS U WITH (NOLOCK) ON U.NR LIKE KSL.CAPIBLOCK_CREATEDBY
JOIN LG_427_KSCARD AS lk ON lk.LOGICALREF = ksl.CARDREF
WHERE ksl.SIGN = 1
AND ksl.AMOUNT >= 300
AND CONVERT(VARCHAR(10), ksl.DATE_, 104) = CONVERT(VARCHAR(10), GETDATE() - #KacGunOnce, 104)
AND ksl.BRANCH =
(
SELECT IsYeriNo
FROM #mad
WHERE logicalref = #s
)
AND lk.CODE =
(
SELECT KasaKodu
FROM #mad
WHERE logicalref = #s
)
) AS f
FOR XML PATH(''tr''), ELEMENTS
) AS NVARCHAR(max));
END; --Kasa hareketlerini HTML formatında XML''e dönüştür
BEGIN
UPDATE #mad
SET
[AlıcıAdresler] = ISNULL(
(
SELECT TOP 1 REPLACE(
(
SELECT RTRIM(MAIL) [data()]
FROM mad.dbo.Kullanicilar k
WHERE k.SIRKET = ''427''
AND IS_YERI = #IsYeriNo
AND LEN(MAIL) > 0
AND DEPERTMAN IN('''+#AliciAdreslerinDepartmani+''')
FOR XML PATH('''')
), '' '', ''; '') AS BIRLESIK
), ''''),
[BilgiAlıcıAdresler] = ISNULL(
(
SELECT TOP 1 REPLACE(
(
SELECT RTRIM(MAIL) [data()]
FROM mad.dbo.Kullanicilar k
WHERE k.SIRKET = ''427''
AND IS_YERI = #IsYeriNo
AND LEN(MAIL) > 0
AND DEPERTMAN IN('''+#BilgiAliciAdreslerinDepartmani+''')
FOR XML PATH('''')
), '' '', ''; '') AS BIRLESIK
), ''''),
[GizliBilgiAlıcıAdresler] = ISNULL(
(
SELECT TOP 1 REPLACE(
(
SELECT RTRIM(MAIL) [data()]
FROM mad.dbo.Kullanicilar k
WHERE k.SIRKET = ''427''
AND LEN(MAIL) > 0
AND DEPERTMAN IN('''+#GizliAliciAdreslerinDepartmani+''')
FOR XML PATH('''')
), '' '', ''; '') AS BIRLESIK
), '''')
WHERE IsYeriNo = #IsYeriNo;
END; -- Değişken tabloya mail adreslerini update et
BEGIN
UPDATE #mad
SET
[AlıcıAdresler] = [BilgiAlıcıAdresler]
WHERE [AlıcıAdresler] = '''';
END; -- Değişken tabloda alici adresi boş olanlara bilgideki adresleri alici olarak ekle
BEGIN
SET #Baslik = '''';
SET #Mesaj = '''';
SET #vucut = '''';
SELECT #Baslik+=CONVERT( NVARCHAR, #IsYeriNo)+'' nolu işyerinin kasa hareketleridir. [212]'';
SELECT #Mesaj+='''';
SET #vucut = ''<html>''+''<body>''+''<H3 style = "color:blue;"><i>''+#Mesaj+''</i> </H3>''+''<H2 style="text-align:center; color:orange;"> Kasa Hareketleri </H2>''+''<H4> ''+''<ul style = "list-style-type:disc">''+''<p>''+''<li>''+#KasaBakiye+''</li>''+''</ul>''+''</p>''+''<H4> ''+''
<table border = 1>
<tr>
<th> Tarih </th> <th> Fiş No </th> <th> İşlem Türü </th> <th> Cari Başlığı </th> <th> Açıklama </th> <th> Tutar </th> <th> Kur </th> <th> Döviz Tutar </th> <th> Özel Kodu </th> <th> Yetki Kodu </th> <th> İş Yeri </th> <th> Kaydeden Kullanıcı </th>
</tr>'';
SET #vucut = #vucut+#xml+''</table></body></html>''+''[''+CONVERT(NVARCHAR, #IsYeriNo)+'' nolu işyerinin ''+
(
SELECT KasaKodu
FROM #mad
WHERE logicalref = #s
)+'' kodlu kasanın ''+CONVERT(NVARCHAR, #KacGunOnce)+'' gün öncesine ait hareketleridir.] Bu maile cevap vererek bilgilendirme maili ile alakalı tavsiyenizi yazabilirsiniz.'';
END; --Mail verilerini hazırla
BEGIN
SET #AliciAdresler =
(
SELECT m.[AlıcıAdresler]
FROM #mad m
WHERE m.logicalref = #s
);
SET #BilgiAliciAdresler =
(
SELECT m.[BilgiAlıcıAdresler]
FROM #mad m
WHERE m.logicalref = #s
);
SET #GizliBilgiAliciAdresler =
(
SELECT m.[GizliBilgiAlıcıAdresler]
FROM #mad m
WHERE m.logicalref = #s
);
END; -- Mail adreslerini değişkenlere tanımla
BEGIN
EXEC msdb.dbo.sp_send_dbmail
#body = #vucut,
#body_format = ''HTML'',
#subject = #Baslik,
#importance = ''HIGH'',
#reply_to = ''mustafaalperen#fimar.com.tr'',
#profile_name = ''MAD_Mail'',
--#recipients = #AliciAdresler,
--#copy_recipients = #BilgiAliciAdresler,
#blind_copy_recipients = #GizliBilgiAliciAdresler,
#execute_query_database = ''FIMAR_MHB'';
END; --Mail Gönder
BEGIN
DECLARE #GonderilenMailBilgisi NVARCHAR(MAX)= ''Mail (Id: ''+CONVERT(NVARCHAR, ##IDENTITY)+'') queued.'';
EXEC sp_MAD_Loglar_Ins
#FORM = ''AGENT_MAD_08_00_Mailleri'',
#KULLANICI = ''Sql Agent'',
#TERMINAL = ''427'',
#ASISTAN = #GonderilenMailBilgisi,
#DERECE = ''Bal'';
END; --Loglama yap
BEGIN
SET #s = #s + 1;
END; --Döngü için döngü değişkenini +1 arttır
/**** DÖNGÜ BİTİŞ ****/
END;
END; -- Mail gönderme döngüsü
';
EXECUTE sp_executesql #SqlQuery;
Consider changing your database design and minimize the use of dynamic SQL. Now your dynamic SQL code will allways be prone to mystical errors and SQL injection attacks.
As suggested by #PPP, you have to get the generated code and see what is wrong with it - to debug it in SQL Server Management Studio.
To do it, you have to use this command:
PRINT CAST(#SqlQuery as ntext)
because your dynamically generated sql is longer than 8000 chars. See this question.
Then copy it to a new window and see the syntax errors and fix them and then fix the code that generates it appropriately.

SQL, search for true, false or both

I am currently trying to code an SQL search that can return TRUE, FALSE, or NEITHER. While the code I currently have works, I do not like the fact that I had to copy and paste a lot of code, and was wondering if there was a way to reduce the amount of code here.
DECLARE #FYear int = 2017
DECLARE #FQuarter char(2) = 'Q2'
DECLARE #FINANCIAL_GOAL_MET bit = NULL
IF(#FINANCIAL_GOAL_MET IS NULL)
SELECT FYear,
FQuarter,
IIF(FINANCIAL_GOAL_MET = 'TRUE', 1,0) AS Financial_Goal_Met
FROM Finances
WHERE (FYear = #FYear)
AND (FQuarter = #FQuarter)
ELSE
SELECT FYear,
FQuarter,
IIF(FINANCIAL_GOAL_MET = 'TRUE', 1,0) AS Financial_Goal_Met
FROM Finances
WHERE (FYear = #FYear)
AND (FQuarter = #FQuarter)
AND FINANCIAL_GOAL_MET = #FINANCIAL_GOAL_MET
You can do this in one query:
DECLARE #FYear int = 2017;
DECLARE #FQuarter char(2) = 'Q2';
DECLARE #FINANCIAL_GOAL_MET bit = NULL;
SELECT FYear, FQuarter,
(CASE WHEN FINANCIAL_GOAL_MET = 'TRUE' THEN 1 ELSE 0
END) AS Financial_Goal_Met
FROM Finances f
WHERE (FYear = #FYear) AND (FQuarter = #FQuarter) AND
(#FINANCIAL_GOAL_MET IS NULL OR FINANCIAL_GOAL_MET = #FINANCIAL_GOAL_MET);
For those not familiar with the bit type in SQL Server, 'TRUE' is accepted for comparison, even though it is a string.

Updating multiple tables inside cursor not working

I have two records in a table A. This helps me to update table 2 however the update is not been applied. This is the SQL code where I added a validation section that allow me to determinate the problem.
DECLARE abc CURSOR FOR
select d.cod_suc, d.cod_ramo_comercial, d.nro_pol, d.cod_item, d.cod_ramo_tecnico, d.cod_tarifa,
d.id_stro, d.nro_stro, d.fec_hora_reclamo, d.fec_aviso, d.fec_registro, d.fec_ingreso_contable,
d.txt_place_of_accident, d.id_substro, d.txt_nombre_cober, d.txt_direccion_bien_siniestrado, d.txt_descripcion_perdida, d.txt_cheque_a_nom, d.cod_manager_code, d.importe_pago_eq
from table1 d
where d.fec_hora_reclamo between '20140801' and '20150731'
and (d.cod_suc = 2 and d.cod_ramo_comercial = 255 and d.nro_pol = 1000001 and d.cod_item = 5)
OPEN abc
FETCH abc INTO #cod_suc, #cod_ramo_comercial, #nro_pol, #cod_item, #cod_ramo_tecnico, #cod_tarifa,
#id_stro, #nro_stro, #fec_hora_reclamo, #fec_aviso, #fec_registro, #fec_ingreso_contable,
#txt_place_of_accident, #id_substro, #txt_nombre_cober, #txt_direccion_bien_siniestrado, #txt_descripcion_perdida, #txt_cheque_a_nom, #cod_manager_code, #importe_pago_eq
WHILE (##FETCH_STATUS = 0)
BEGIN
select #varIDPV = min(id_pv), #varCodTarifa = min(cod_tarifa)
from #portfolio p
where p.cod_suc = #cod_suc and p.cod_ramo_comercial = #cod_ramo_comercial and p.Poliza = #nro_pol and p.Item = #cod_item and p.cod_ramo_tecnico = #cod_ramo_tecnico
and p.[ID Incident] IS NULL
/**************************************************************************************************************
-- Validation section
-- First record:
mid(id_pv) = 100, min(cod_tarifa) = 1
-- Second record:
mid(id_pv) = 100, min(cod_tarifa) = 1
--> Should be mid(id_pv) = 100, min(cod_tarifa) = 2
*/
select min(id_pv), min(cod_tarifa)
from #portfolio p
where p.cod_suc = #cod_suc and p.cod_ramo_comercial = #cod_ramo_comercial and p.Poliza = #nro_pol and p.Item = #cod_item and p.cod_ramo_tecnico = #cod_ramo_tecnico
and p.[ID Incident] IS NULL
/**************************************************************************************************************/
update p set p.[ID Incident] = #id_stro, p.[No. Incident] = #nro_stro,
p.[Fecha Accidente] = #fec_hora_reclamo, p.[Fecha Notificacion] = #fec_aviso, p.[Fecha Registro] = #fec_registro, p.[Fecha Pago] = #fec_ingreso_contable,
p.[Lugar Accidente] = #txt_place_of_accident, p.[ID Subsiniestro] = #id_substro, p.[Cobertura Amparo] = #txt_nombre_cober, p.[Direccion Bien Siniestrado] = #txt_direccion_bien_siniestrado, p.[Descripcion Perdida] = #txt_descripcion_perdida, p.[Pago A] = #txt_cheque_a_nom, p.[Referida] = #cod_manager_code,
[Incurrido R12] = #importe_pago_eq, [Incurrido Cerrados R12] = #importe_pago_eq
from #portfolio p
where p.cod_suc = #cod_suc and p.cod_ramo_comercial = #cod_ramo_comercial and p.Poliza = #nro_pol and p.Item = #cod_item and p.cod_ramo_tecnico = #cod_ramo_tecnico
and p.[ID Incident] IS NULL and p.id_pv = #varIDPV and p.cod_tarifa = #varCodTarifa
FETCH abc INTO #cod_suc, #cod_ramo_comercial, #nro_pol, #cod_item, #cod_ramo_tecnico, #cod_tarifa,
#id_stro, #nro_stro, #fec_hora_reclamo, #fec_aviso, #fec_registro, #fec_ingreso_contable,
#txt_place_of_accident, #id_substro, #txt_nombre_cober, #txt_direccion_bien_siniestrado, #txt_descripcion_perdida, #txt_cheque_a_nom, #cod_manager_code, #importe_pago_eq
END
CLOSE abc
DEALLOCATE abc
When I see the result, only the first record is updated.
I found the problem. I forgot to add one condition more in update (inside where). Thanks for the support