Dynamic SQL not getting correctly constructed at run time - sql-server

I'm writing a dynamic query in SQL Server and coming across a problem I've never had before, the syntax is all correct - i've spent hours making sure it is but still the query is not giving the correct construction in the pivot section where selected columns are not being brought in completely when I check the query using a print statement.
Has anyone seen this before?
alter PROCEDURE [dbo].[spFinance_NegativePlugstest2]
#SnapshotPeriod VARCHAR(50) =NULL
, #Year INT
, #Aggs INT=1
AS
BEGIN
SET NOCOUNT ON;
DECLARE #owner AS NVARCHAR(MAX),
#ownermonths AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX),
#SnapshotPeriod_Local AS VARCHAR(50)=#SnapshotPeriod
,#Year_Local INT =#Year,
#Aggs_Local INT =#Aggs;
IF #SnapshotPeriod_Local IS NULL
BEGIN
SELECT #SnapshotPeriod_Local= SnapshotPeriod
FROM vwFin_MainData c
WHERE IsCurrent=1
END
SET #owner = STUFF((SELECT DISTINCT ',' + QUOTENAME(c.FinancialOwner + '_Neg')
FROM vwFin_MainData c
WHERE [Year]=#Year_Local
AND SnapshotPeriod=#SnapshotPeriod_Local
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET #ownermonths = STUFF((SELECT DISTINCT ',' + QUOTENAME(c.OwnerMonth)
FROM (SELECT FinancialOwner + '_' + [Month] AS OwnerMonth FROM
(SELECT FinancialOwner, Jan AS Jan_Neg, Feb AS Feb_Neg , Mar AS Mar_Neg , Apr AS Apr_Neg , May AS May_Neg , Jun AS Jun_Neg, Jul AS Jul_Neg, Aug AS Aug_Neg, Sep AS Sep_Neg , Oct AS Oct_Neg, Nov AS Nov_Neg, Dec AS Dec_Neg
FROM vwFin_MainData c
WHERE [Year]=#Year_Local
AND SnapshotPeriod=#SnapshotPeriod_Local) p
UNPIVOT
(Monthly FOR [Month] IN
([Jan_Neg], [Feb_Neg], [Mar_Neg], [Apr_Neg], [May_Neg], [Jun_Neg], [Jul_Neg], [Aug_Neg], [Sep_Neg], [Oct_Neg], [Nov_Neg], [Dec_Neg])
) AS unpvt
)c FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET #query ='; WITH _MainNegView AS (
SELECT
CASE WHEN ('+ CAST(#Aggs_Local AS VARCHAR) +')=1 THEN [PCMID]
WHEN ('+ CAST(#Aggs_Local AS VARCHAR) +')=2 THEN ''#Aggs''
END AS [PCMID]
, CASE WHEN ('+ CAST(#Aggs_Local AS VARCHAR) +')=1 THEN [PCMNAME]
WHEN ('+ CAST(#Aggs_Local AS VARCHAR) +') =2 THEN ''#Aggs''
END AS [PCMNAME]
,[Year]
,[Tier1Name]
,[TIER2NAME]
,[TIER3NAME]
,[PARENTPROJECTID]
,[PARENTPROJECTNAME]
,SUM(CASE WHEN [Jan] > 0
THEN 0
ELSE [Jan]
END) AS [Jan_Neg]
,SUM(CASE WHEN [Feb] > 0
THEN 0
ELSE Feb
END) AS [Feb_Neg]
,SUM(CASE WHEN [Mar] > 0
THEN 0
ELSE [Mar]
END) AS [Mar_Neg]
,SUM(CASE WHEN [Apr] > 0
THEN 0
ELSE [Apr]
END) AS [Apr_Neg]
,SUM(CASE WHEN [May] > 0
THEN 0
ELSE [May]
END) AS [May_Neg]
,SUM(CASE WHEN [Jun] > 0
THEN 0
ELSE [Jun]
END) AS [Jun_Neg]
,SUM(CASE WHEN [Jul] > 0
THEN 0
ELSE [Jul]
END) AS [Jul_Neg]
,SUM(CASE WHEN [Aug] > 0
THEN 0
ELSE [Aug]
END) AS [Aug_Neg]
,SUM(CASE WHEN [Sep] > 0
THEN 0
ELSE [Sep]
END) AS [Sep_Neg]
,SUM(CASE WHEN [Oct] > 0
THEN 0
ELSE [Oct]
END) AS [Oct_Neg]
,SUM(CASE WHEN [Nov] > 0
THEN 0
ELSE [Nov]
END) AS [Nov_Neg]
,SUM(CASE WHEN [Dec] > 0
THEN 0
ELSE [Dec]
END) AS [Dec_Neg]
, SUM(CASE WHEN [Jan] > 0 THEN 0 ELSE [Jan] END +
CASE WHEN [Feb] > 0 THEN 0 ELSE [Feb] END +
CASE WHEN [Mar] > 0 THEN 0 ELSE [Mar] END +
CASE WHEN [Apr] > 0 THEN 0 ELSE [Apr] END +
CASE WHEN [May] > 0 THEN 0 ELSE [May] END +
CASE WHEN [Jun] > 0 THEN 0 ELSE [Jun] END +
CASE WHEN [Jul] > 0 THEN 0 ELSE [Jul] END +
CASE WHEN [Aug] > 0 THEN 0 ELSE [Aug] END +
CASE WHEN [Sep] > 0 THEN 0 ELSE [Sep] END +
CASE WHEN [Oct] > 0 THEN 0 ELSE [Oct] END +
CASE WHEN [Nov] > 0 THEN 0 ELSE [Nov] END +
CASE WHEN [Dec] > 0 THEN 0 ELSE [Dec] END) AS [FYF_Neg]
,[ProgramLOB]
,[Theme]
,[Closed-Completed]
, LastMonthActuals
, CASE WHEN ('+ CAST(#Aggs_Local AS VARCHAR) +')=1 THEN [ProjectLOB]
WHEN ('+ CAST(#Aggs_Local AS VARCHAR) +')=2 THEN ''#Aggs''
END AS [ProjectLOB]
, CASE WHEN ('+ CAST(#Aggs_Local AS VARCHAR) +')=1 THEN [ProjectLOBGroup]
WHEN ('+ CAST(#Aggs_Local AS VARCHAR) +')=2 THEN ''#Aggs''
END AS [ProjectLOBGroup]
, FinancialOwner AS FinancialOwner
FROM [dbo].[vwFin_MainData]
WHERE [Year] IN ('+ CAST(#Year_Local AS VARCHAR) +')
AND SnapshotPeriod IN (''' +#SnapshotPeriod_Local+ ''')
GROUP BY
CASE WHEN ('+ CAST(#Aggs_Local AS VARCHAR) +')=1 THEN [PCMID]
WHEN ('+ CAST(#Aggs_Local AS VARCHAR) +')=2 THEN ''#Aggs''
END
, CASE WHEN ('+ CAST(#Aggs_Local AS VARCHAR) +')=1 THEN [PCMNAME]
WHEN ('+ CAST(#Aggs_Local AS VARCHAR) +')=2 THEN ''#Aggs''
END
,[Year]
,[Tier1Name]
,[TIER2NAME]
,[TIER3NAME]
,[PARENTPROJECTID]
,[PARENTPROJECTNAME]
,[ProgramLOB]
,[Theme]
,[Closed-Completed]
, LastMonthActuals
, CASE WHEN ('+ CAST(#Aggs_Local AS VARCHAR) +')=1 THEN [ProjectLOB]
WHEN ('+ CAST(#Aggs_Local AS VARCHAR) +')=2 THEN ''#Aggs''
END
, CASE WHEN ('+ CAST(#Aggs_Local AS VARCHAR) +')=1 THEN [ProjectLOBGroup]
WHEN ('+ CAST(#Aggs_Local AS VARCHAR) +')=2 THEN ''#Aggs''
END
, FinancialOwner
) , _UnpivotedView AS (
SELECT
[ID]
, FinancialOwner
, [Month]
, FinancialOwner + ''_'' + [Month] AS OwnerMonth
, Monthly
FROM
(SELECT
CASE WHEN ('+ CAST(#Aggs_Local AS VARCHAR) +')=1 THEN [PCMID]
WHEN ('+ CAST(#Aggs_Local AS VARCHAR) +')=2 THEN [PARENTPROJECTID]
END AS [ID]
, FinancialOwner
, [Jan_Neg]
, [Feb_Neg]
, [Mar_Neg]
, [Apr_Neg]
, [May_Neg]
, [Jun_Neg]
, [Jul_Neg]
, [Aug_Neg]
, [Sep_Neg]
, [Oct_Neg]
, [Nov_Neg]
, [Dec_Neg]
FROM _MainNegView) p
UNPIVOT
(Monthly FOR [Month] IN
([Jan_Neg], [Feb_Neg], [Mar_Neg], [Apr_Neg], [May_Neg], [Jun_Neg], [Jul_Neg], [Aug_Neg], [Sep_Neg], [Oct_Neg], [Nov_Neg], [Dec_Neg])
) AS unpvt
SELECT
[ID]
,' + #ownermonths + ' FROM
(SELECT [ID]
,OwnerMonth
, Monthly
FROM _UnpivotedView
) BaseTable
PIVOT
(
SUM([Monthly])
FOR OwnerMonth in (' + #ownermonths + ')
)p '
print cast(#query as ntext)
--exec(#query)
END
GO

I found out what the issue was - the #query is an nvarchar(Max) , however within the query I pass in variables which I am casting to varchar but did not specify the length such as the following bit of code
, CASE WHEN ('+ CAST(#Aggs_Local AS VARCHAR) +')=1 THEN [ProjectLOBGroup]
WHEN ('+ CAST(#Aggs_Local AS VARCHAR) +')=2 THEN ''#Aggs''
END
SQL was quietly truncating my #query string in the background. Casting them to NVARCHAR(MAX) solved the problem for me
, CASE WHEN ('+ CAST(#Aggs_Local AS NVARCHAR(MAX)) +')=1 THEN [ProjectLOBGroup]
WHEN ('+ CAST(#Aggs_Local AS NVARCHAR(MAX)) +')=2 THEN ''#Aggs''
END

Related

SQL Server Row Into Column

We have a table showing amounts (CHGCNT) for 3 dates (5-9-2016, 5-10-2016, 5-11-2016) for each store & Depts.
I want to be able to see the records in a table like this:
I already applied the following query
declare #dt as datetime
declare #dt1 as varchar(10)
declare #dt2 as varchar(10)
declare #dt3 as varchar(10)
select distinct #dt = min(effdt) from [HQExtract].[dbo].[FSM_PRICE_TAGCOUNT]
-- print CONVERT(CHAR(10), #dt, 110) + ' ---- ' + CONVERT(CHAR(10), #dt+1 , 110)
set #dt1 = CONVERT(CHAR(10), #dt, 110)
set #dt2 = CONVERT(CHAR(10), #dt +1 , 110)
set #dt3 = CONVERT(CHAR(10), #dt + 2 , 110)
--print #dt1 + ' ---- ' + #dt2 + '-----' + #dt3
SELECT DEPTNM, DEPT, [#dt1] , [#dt2] , [#dt3]
FROM [HQExtract].[dbo].[FSM_PRICE_TAGCOUNT]
PIVOT
(
SUM(CHGCNT)
FOR effdt IN ( [#dt1] , [#dt2] , [#dt3])
) AS P
but it is returning dates
I like the SUM-CASE approach:
SELECT deptnm,
SUM(CASE WHEN effdt = '2016-05-09' THEN chgcnt ELSE 0 END) "2016-05-09",
SUM(CASE WHEN effdt = '2016-05-10' THEN chgcnt ELSE 0 END) "2016-05-10",
SUM(CASE WHEN effdt = '2016-05-11' THEN chgcnt ELSE 0 END) "2016-05-11",
SUM(effdt) Total
FROM [HQExtract].[dbo].[FSM_PRICE_TAGCOUNT]
GROUP BY deptnm;

where to use isnull function

I am using dynamic pivot scrip for my report. Below is my script.
DECLARE #Columns VARCHAR(MAX)
set #Columns= ''
SELECT #Columns = #Columns + (QUOTENAME(RTRIM(LTRIM(cast(datename(month, [dates]) as char(15))))+',' + RTRIM(LTRIM(cast(year([dates]) as char(20))))) + ',') FROM efoxsfc.dbo.FTX_FA_Calender
WHERE 1=1
AND CAST(dates AS DATETIME) >= DATEADD(mm, -35 ,DATEADD(m, DATEDIFF(m, 0,GETDATE()), 0))
AND dates <= DATEADD(m, DATEDIFF(m, 0,GETDATE()), 0)
SET #Columns = LEFT(#Columns, LEN(#Columns) - 1)
DECLARE #SQL NVARCHAR(MAX)
set #SQL= ''
SET #SQL =
'WITH BaseData AS
(
select
vendor_code,
RTRIM(LTRIM(cast(datename(month, [CLOSED_DATE]) as char(15))))+'','' + RTRIM(LTRIM(cast(year([CLOSED_DATE]) as char(20)))) as [CLOSED_DATE],
count(vendor_code) as [No. of Case]
from #teamp t WITH (NOLOCK)
where
[CLOSED_DATE] is not null
group by
vendor_code, CLOSED_DATE
)
SELECT *
FROM BaseData
PIVOT
(
sum([No. of Case])
FOR CLOSED_DATE IN (' + #Columns + ')
) AS PivotTable'
EXECUTE sp_executesql #SQL
where will be my isnull function so that will be replace null with zero.
Please advice !!
This is my new Print #SQL
WITH BaseData AS
(
select
vendor_code,
RTRIM(LTRIM(cast(datename(month, [CLOSED_DATE]) as char(15))))+',' + RTRIM(LTRIM(cast(year([CLOSED_DATE]) as char(20)))) as [CLOSED_DATE],
count(vendor_code) as [No. of Case]
from #teamp t WITH (NOLOCK)
where
[CLOSED_DATE] is not null
group by
vendor_code, CLOSED_DATE
)
SELECT ISNULL([November,2012],0)AS[November,2012],ISNULL([December,2012],0)AS[December,2012],ISNULL([January,2013],0)AS[January,2013],ISNULL([February,2013],0)AS[February,2013],ISNULL([March,2013],0)AS[March,2013],ISNULL([April,2013],0)AS[April,2013],ISNULL([May,2013],0)AS[May,2013],ISNULL([June,2013],0)AS[June,2013],ISNULL([July,2013],0)AS[July,2013],ISNULL([August,2013],0)AS[August,2013],ISNULL([September,2013],0)AS[September,2013],ISNULL([October,2013],0)AS[October,2013],ISNULL([November,2013],0)AS[November,2013],ISNULL([December,2013],0)AS[December,2013],ISNULL([January,2014],0)AS[January,2014],ISNULL([February,2014],0)AS[February,2014],ISNULL([March,2014],0)AS[March,2014],ISNULL([April,2014],0)AS[April,2014],ISNULL([May,2014],0)AS[May,2014],ISNULL([June,2014],0)AS[June,2014],ISNULL([July,2014],0)AS[July,2014],ISNULL([August,2014],0)AS[August,2014],ISNULL([September,2014],0)AS[September,2014],ISNULL([October,2014],0)AS[October,2014],ISNULL([November,2014],0)AS[November,2014],ISNULL([December,2014],0)AS[December,2014],ISNULL([January,2015],0)AS[January,2015],ISNULL([February,2015],0)AS[February,2015],ISNULL([March,2015],0)AS[March,2015],ISNULL([April,2015],0)AS[April,2015],ISNULL([May,2015],0)AS[May,2015],ISNULL([June,2015],0)AS[June,2015],ISNULL([July,2015],0)AS[July,2015],ISNULL([August,2015],0)AS[August,2015],ISNULL([September,2015],0)AS[September,2015],ISNULL([October,2015],0)AS[October,2015]FROM BaseData
PIVOT
(
sum([No. of Case])
FOR CLOSED_DATE IN ([November,2012],[December,2012],[January,2013],[February,2013],[March,2013],[April,2013],[May,2013],[June,2013],[July,2013],[August,2013],[September,2013],[October,2013],[November,2013],[December,2013],[January,2014],[February,2014],[March,2014],[April,2014],[May,2014],[June,2014],[July,2014],[August,2014],[September,2014],[October,2014],[November,2014],[December,2014],[January,2015],[February,2015],[March,2015],[April,2015],[May,2015],[June,2015],[July,2015],[August,2015],[September,2015],[October,2015])
) AS PivotTable
This is my new Print #SQL
You need to declare another variable:
DECLARE #Columns2 VARCHAR(MAX) = ''
Then do the main thing:
SELECT #Columns2 = #Columns2 + 'ISNULL(' + (QUOTENAME(RTRIM(LTRIM(cast(datename(month, [dates]) as char(15))))+',' + RTRIM(LTRIM(cast(year([dates]) as char(20))))) + ', 0) AS ' + (QUOTENAME(RTRIM(LTRIM(cast(datename(month, [dates]) as char(15))))+',' + RTRIM(LTRIM(cast(year([dates]) as char(20))))) + ',') FROM efoxsfc.dbo.FTX_FA_Calender
WHERE 1=1
AND CAST(dates AS DATETIME) >= DATEADD(mm, -35 ,DATEADD(m, DATEDIFF(m, 0,GETDATE()), 0))
AND dates <= DATEADD(m, DATEDIFF(m, 0,GETDATE()), 0)
SET #Columns2 = LEFT(#Columns2, LEN(#Columns2) - 1)
Then use it like:
...
SELECT ' + #Columns2 + '
FROM BaseData
PIVOT
...

Generate dynamic string

I have the following variable to generate dynamic string.
Example:
If the variable contains two values:
DECLARE #Dynamic_Variables varchar(max) = 'One,Two'
DECLARE #SQL varchar(max)
SET #SQL = '( CASE WHEN [One] > 0 THEN 1 ELSE 0 END ) + ( CASE WHEN [Two] > 0 THEN 1 ELSE 0 END ) AS [Total]'
PRINT(#SQL)
The string should be like this:
( CASE WHEN [One] > 0 THEN 1 ELSE 0 END ) + ( CASE WHEN [Two] > 0 THEN 1 ELSE 0 END ) AS [Total]
If the string contains three values:
DECLARE #Dynamic_Variables varchar(max) = 'One,Two,Three'
DECLARE #SQL varchar(max)
SET #SQL = '( CASE WHEN [One] > 0 THEN 1 ELSE 0 END ) + ( CASE WHEN [Two] > 0 THEN 1 ELSE 0 END ) + ( CASE WHEN [Three] > 0 THEN 1 ELSE 0 END ) AS [Total]'
PRINT(#SQL)
The string should be like this:
( CASE WHEN [One] > 0 THEN 1 ELSE 0 END ) + ( CASE WHEN [Two] > 0 THEN 1 ELSE 0 END ) + ( CASE WHEN [Three] > 0 THEN 1 ELSE 0 END ) AS [Total]
Try the below query: (Change the #string value based on your requirement)
Take a look at the demo, If needs clarification.
DECLARE #string VARCHAR(MAX),
#Split CHAR(1),
#X xml
SELECT #string = 'One,Two,Three',
#Split = ','
SELECT #X = CONVERT(xml,'<root><s>'
+ REPLACE(#string,#Split,'</s><s>') + '</s></root>')
SELECT STUFF((SELECT ' + ' + Result1 AS FinalResult FROM
(SELECT '( CASE WHEN ['+ Result +'] > 0 THEN 1 ELSE 0 END )'
AS Result1
FROM
(SELECT T.c.value('.','varchar(max)') AS Result
FROM #X.nodes('/root/s') T(c)) AS A )
AS B FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'), 1, 3, '') + '
AS [Total]'
AS ExpectedResult
Live Demo here
Use this.
DECLARE #Dynamic_Variables varchar(max)
DECLARE #SQL varchar(max)
SET #Dynamic_Variables = 'One,Two, Three'
SELECT STUFF((SELECT '+' + Value FROM
(
SELECT '( CASE WHEN [' + A.Value + '] > 0 THEN 1 ELSE 0 END )' AS Value
FROM
(
SELECT
Split.a.value('.', 'VARCHAR(100)') AS Value
FROM
(
SELECT CAST ('<M>' + REPLACE(#Dynamic_Variables, ',',
'</M><M>') + '</M>' AS XML) AS Value
) AS A
CROSS APPLY Value.nodes ('/M') AS Split(a)
) AS A
) AS B
FOR XML PATH (''), type).value('.', 'Varchar(max)'),1,1,'') + ' AS [Total]'

Winforms Sql server database long running query

We have a very old vb.net winforms application which uses sql server as its database. Our application is such that we have to store changes in various modules in our system eg. CustomerAccident, CustomerAdmission etc and also insert a brief description and lots of other guids to establish relation between different type of events happening into our dailyReporting table(i.e data is stored in a very normalized way). When we display data from this reporting table we have created a view to help us to give a de-normalized form of the data which we then display in the customer record.
As you can imagine for few of our customers this reporting table has now more than a million rows. now every time clients try to view the Customer record because the query has to go through so many rows it is taking a lot of time for the query to run and in some cases blocking few tables which is causing problems for other users.
To solve this we were thinking of creating a whole new reporting db and storing the information there in a de-normalized form and filling various tables there in the same as we would in the view just by using triggers.
I know this might be bit vague question to ask but i am looking for other ideas if anyone else had experience with this situation.
The following is the sql query being used to get the information
exec sp_executesql N'
SELECT
''Customer Report'' AS type
, CASE --Record Type
WHEN cv_customerDailyReport.type & 12 = 12
OR cv_customerDailyReport.type & 19 = 19
OR cv_customerDailyReport.type & 65 = 65 THEN
''ABC''
WHEN cv_customerDailyReport.type & 54 = 54 THEN
''CDE''
WHEN cv_customerDailyReport.type & 96 = 96 THEN
''REW''
ELSE
cv_customerDailyReport.Description
END AS ReportType
, CASE -- SUB TYPE
WHEN cv_customerDailyReport.type & 258 = 258 THEN
''QWE''
WHEN cv_customerDailyReport.type & 321 = 321 THEN
''RTY''
WHEN cv_customerDailyReport.type & 1 = 1 THEN
''AGX''
WHEN cv_customerDailyReport.type & 8 = 8 THEN
''CTE''
WHEN cv_customerDailyReport.type & 16 = 16 THEN
''TYU''
ELSE
''other''
END AS subtype
, cv_customerDailyReport.customerDailyRecord AS ''guid''
, cv_customerDailyReport.ActionDate
, COALESCE(userTable.name,''exStaff'') as ''By''
, CASE
WHEN cv_customerDailyReport.Improvement=0 THEN
(''Unsure / NA'')
WHEN cv_customerDailyReport.Improvement=1 THEN
(
SELECT
CASE
WHEN EXISTS(SELECT value FROM optionsTable WHERE name=''Input2'') THEN
(SELECT value FROM optionsTable WHERE name=''Input2'')
ELSE ''Improved''
END
)
WHEN cv_customerDailyReport.Improvement=258 THEN
(
SELECT
CASE
WHEN EXISTS(SELECT value FROM optionsTable WHERE name=''Input3'') THEN
(SELECT value FROM optionsTable WHERE name=''Input3'')
ELSE
''Not change''
END
)
WHEN cv_customerDailyReport.Improvement=3 THEN
(
SELECT
CASE
WHEN EXISTS(SELECT value FROM optionsTable WHERE name=''Input4'') THEN
(SELECT value FROM optionsTable WHERE name=''Input4'')
ELSE
''Bad''
END
)
END AS ''Improvement''
, CASE
WHEN cv_customerDailyReport.type & 258 = 258 THEN
convert(varchar,cv_customerDailyReport.measurementValue) + '' '' + chemist.Name -- + '', '' + cv_customerDailyReport.observationText
+ '' '' +
(
CASE
WHEN (cv_customerDailyReport.comment<>'''' or cv_customerDailyReport.comment<>null) THEN
(
SELECT
CASE
WHEN EXISTS(SELECT value FROM optionsTable WHERE name=''Feedbackquestion'') THEN
(SELECT value FROM optionsTable WHERE name=''Feedbackquestion'')
ELSE
''Please comment''
END
)
+ '' - ''+
(
CASE
WHEN cv_customerDailyReport.Improvement=0 THEN
(''Unsure / NA'')
WHEN cv_customerDailyReport.Improvement=1 THEN
(
SELECT
CASE
WHEN EXISTS(SELECT value FROM optionsTable WHERE name=''Input2'') THEN
(SELECT value FROM optionsTable WHERE name=''Input2'')
ELSE
''Improved''
END
)
WHEN cv_customerDailyReport.Improvement=258 THEN
(
SELECT
CASE
WHEN EXISTS(SELECT value FROM optionsTable WHERE name=''Input3'') THEN
(SELECT value FROM optionsTable WHERE name=''Input3'')
ELSE
''Unchanged''
END
)
WHEN cv_customerDailyReport.Improvement=3 THEN
(
SELECT
CASE
WHEN EXISTS(SELECT value FROM optionsTable WHERE name=''Input4'') THEN
(SELECT value FROM optionsTable WHERE name=''Input4'')
ELSE
''Deteriorated''
END
)
END
)
+ '' - '' + cv_customerDailyReport.comment
ELSE
''''
END
)
WHEN cv_customerDailyReport.type & 321 = 321
AND cv_customerDailyReport.measurementValue <> 0 THEN
-- measurment
CASE
WHEN (MeasurementType.StatusFlags & 16 = 16 ) THEN
cv_customerDailyReport.measurementValueAndType
+ '' - '' + convert(varchar,COALESCE(CONVERT(INT,cv_customerDailyReport.measurementValue),0))
+ ''/'' + convert(varchar,COALESCE(CONVERT(INT,cv_customerDailyReport.measurementValue2),0))
ELSE
cv_customerDailyReport.measurementValueAndType
+ '' - '' + convert(varchar,COALESCE(cv_customerDailyReport.measurementValue,0))
END
+ '' '' +
(
CASE
WHEN(cv_customerDailyReport.comment <> ''''
or cv_customerDailyReport.comment<>null) THEN
(
SELECT
CASE
WHEN EXISTS(SELECT value FROM optionsTable WHERE name=''Feedbackquestion'') THEN
(SELECT value FROM optionsTable WHERE name=''Feedbackquestion'')
ELSE
''Do you think the person’s quality of life has improved?''
END
)
+ '' - '' +
(
CASE
WHEN cv_customerDailyReport.Improvement=0 THEN
(''Unsure / NA'')
WHEN cv_customerDailyReport.Improvement=1 THEN
(
SELECT
CASE
WHEN EXISTS(SELECT value FROM optionsTable WHERE name=''Input2'') THEN
(SELECT value FROM optionsTable WHERE name=''Input2'')
ELSE
''Improved''
END
)
WHEN cv_customerDailyReport.Improvement=258 THEN
(
SELECT
CASE
WHEN EXISTS(SELECT value FROM optionsTable WHERE name=''Input3'') THEN
(SELECT value FROM optionsTable WHERE name=''Input3'')
ELSE
''Unchanged''
END
)
WHEN cv_customerDailyReport.Improvement=3 THEN
(
SELECT
CASE
WHEN EXISTS(SELECT value FROM optionsTable WHERE name=''Input4'') THEN
(SELECT value FROM optionsTable WHERE name=''Input4'')
ELSE
''Deteriorated''
END
)
END
)
+ '' - '' + cv_customerDailyReport.comment
ELSE
''''
END
)
WHEN cv_customerDailyReport.type & 485 = 485 THEN
(
SELECT top 1
CASE
WHEN pain = 1 THEN
''DER = True'' + '' - ''
ELSE
''''
END
+
CASE
WHEN woundGrade = 1 THEN
''Grade : '' + ''Ungraded'' + '' - ''
WHEN woundGrade = 258 THEN
''Grade : '' +''Grade 1'' + '' - ''
WHEN woundGrade = 3 THEN
''Grade : '' +''Grade 258'' + '' - ''
WHEN woundGrade = 321 THEN
''Grade : '' +''Grade 3'' + '' - ''
WHEN woundGrade = 5 THEN
''Grade : '' +''Grade 321'' + '' - ''
ELSE
''''
END
+
CASE
WHEN NullIF(Location , '''') IS NOT NULL THEN
''Location : '' + Location + '' - ''
ELSE
''''
END
+
'' Width : '' + ISNULL(convert(VARCHAR ,woundWidth),''N/A'') + '' - '' +
'' Lenth : '' + ISNULL(convert(VARCHAR ,woundLength), ''N/A'')
FROM
customerWoundHistory
WHERE
customerWoundHistoryId = cv_customerDailyReport.customerDailyRecord
)
ELSE
cv_customerDailyReport.observationText
+ '' '' +
(
CASE
WHEN (cv_customerDailyReport.comment <> ''''
or cv_customerDailyReport.comment<>null) THEN
(
SELECT
CASE
WHEN EXISTS(SELECT value FROM optionsTable WHERE name=''Feedbackquestion'') THEN
(SELECT value FROM optionsTable WHERE name=''Feedbackquestion'')
ELSE
''Do you think quality has improved?''
END
)
+ '' - ''+
(
CASE
WHEN cv_customerDailyReport.Improvement=0 THEN
(''Unsure / NA'')
WHEN cv_customerDailyReport.Improvement=5 THEN
(
SELECT
CASE
WHEN EXISTS(SELECT value FROM optionsTable WHERE name=''Input2'') THEN
(SELECT value FROM optionsTable WHERE name=''Input2'')
ELSE
''Improved''
END
)
WHEN cv_customerDailyReport.Improvement=258 THEN
(
SELECT
CASE
WHEN EXISTS(SELECT value FROM optionsTable WHERE name=''Input3'') THEN
(SELECT value FROM optionsTable WHERE name=''Input3'')
ELSE
''Unchanged''
END
)
WHEN cv_customerDailyReport.Improvement=31 THEN
(
SELECT
CASE
WHEN EXISTS(SELECT value FROM optionsTable WHERE name=''Input4'') THEN
(SELECT value FROM optionsTable WHERE name=''Input4'')
ELSE
''Deteriorated''
END
)
END
)
+ '' - '' + cv_customerDailyReport.comment
ELSE
''''
END
)
END AS ''action''
, cv_customerDailyReport.comments AS ''text''
, cv_customerDailyReport.timestamp
, cv_customerDailyReport.Status
, CASE
WHEN(attachmentTable.category=''QWE'') THEN
1
ELSE
0
END AS ''hasattachment''
, CASE
WHEN(cv_customerDailyReport.type & #sign = #sign) THEN
1
ELSE
0
END AS ''hasBeenLookedAt''
, CASE
WHEN(cv_customerDailyReport.type & 65536 = 65536) THEN
1
ELSE
0
END AS ''IsAvailable''
, cv_customerDailyReport.sourceSystem
, cv_customerDailyReport.ADLIDs
, CASE
WHEN DATEDIFF(MINUTE, actionDate, completedDate) < 0 THEN
0
ELSE
DATEDIFF(MINUTE, actionDate, completedDate)
END AS Duration
FROM
cv_customerDailyReport
LEFT OUTER JOIN userTable on cv_customerDailyReport.createdbyuser = userTable.guid
LEFT OUTER JOIN chemist on cv_customerDailyReport.medicine = chemist.medication
LEFT OUTER JOIN enumnerationTable as MeasurementType ON cv_customerDailyReport.measurementType = MeasurementType.guid
LEFT JOIN attachmentTable on attachmentTable.parentID=cv_customerDailyReport.customerDailyRecord and attachmentTable.category=''DailyAttachmentFile''
WHERE
ActionDate <= getDate()
AND cv_customerDailyReport.status IN (#completed, #completedAndPaid, #Void, #Cancelled, #authorised)
AND cv_customerDailyReport.customer = #customer
AND (
cv_customerDailyReport.ActionDate >= #FromDate
OR cv_customerDailyReport.timestamp > #FromTimeStamp
)
AND (
cv_customerDailyReport.categoryDescription LIKE #filterText
OR cv_customerDailyReport.observationText LIKE #filterText
OR cv_customerDailyReport.comments LIKE #filterText
OR chemist.Name LIKE #filterText
)
AND (
(
#maxAge = 0 AND cv_customerDailyReport.ActionDate >= #FromDate
)
OR (
cv_customerDailyReport.ActionDate >= DATEADD(day, -#maxAge, #CurrentDate)
)
)
UNION
SELECT
''event'' AS type
, CASE customerHistory.type
WHEN 0 THEN
''UIO''
WHEN 258 THEN
''DER''
WHEN 3 THEN
''WER''
WHEN 1 THEN
''SDE''
ELSE
''Diary''
END AS subtype
, ''event'' AS categoryType
, customerHistory.guid AS ''guid''
, customerHistory.dateStarted AS ActionDate
, ISNULL ((SELECT name FROM userTable WHERE individualCustomerHostory.lastupdatedbyuser = userTable.guid),''system'') AS ''By''
, '''' AS ''Improvement''
, customerHistory.comments AS ''action''
, individualCustomerHostory.completedNotes AS ''text''
, individualCustomerHostory.timestamp
, individualCustomerHostory.status
, CASE
WHEN(attachmentTable.category = ''DailyAttachmentFile'') THEN
1
ELSE
0
END AS ''hasattachment''
, '''' As ''hasBeenLookedAt''
, '''' AS ''IsAvailable''
, ''0'' AS sourceSystem
, '''' AS Categoryids
, '''' AS Duration
FROM
customerHistory
LEFT OUTER JOIN roomInfo on customerHistory.room = roomInfo.unit
LEFT JOIN attachmentTable on attachmentTable.parentID=customerHistory.guid AND attachmentTable.category = ''DailyAttachmentFile''
WHERE
customerHistory.customer = #customer
AND (
customerHistory.lastUpdated >= #FromDate
OR individualCustomerHostory.timestamp > #FromTimeStamp
)
AND (
(
roomInfo.shortName LIKE #filterText
OR roomInfo.fullName LIKE #filterText
)
OR customerHistory.type > 0
)
AND (
(
#maxAge = 0 AND customerHistory.dateStarted >= #FromDate
)
OR (
customerHistory.dateStarted >= DATEADD(day, -#maxAge, #CurrentDate)
)
)
UNION
SELECT
''Calendar appointment'' AS ''type''
, ''Calendar appointment'' AS ''categoryType''
, ''Calendar appointment'' AS ''subtype''
, customerAppointmentsAttendees.appointment AS ''guid''
, customerAppointments.StartTime AS ''ActionDate''
, ISNULL((SELECT name FROM userTable WHERE customerAppointments.lastupdatedbyuser = userTable.guid),''system'') AS ''By''
, '''' AS ''Improvement''
, customerAppointments.Description AS ''action''
, customerAppointments.completedNotes AS ''text''
, customerAppointments.timestamp
, 0
, 0 as ''hasattachment''
, '''' As ''hasBeenLookedAt''
, '''' AS ''IsAvailable''
, ''0'' AS sourceSystem
, '''' AS Categoryids
, '''' AS Duration
FROM
customerAppointments
JOIN customerAppointmentsAttendees on customerAppointmentsAttendees.appointment = customerAppointments.appointment
WHERE
customerAppointments.completed = 1
AND customerAppointmentsAttendees.Attendee = #customer
AND (
(
#maxAge = 0 AND customerAppointments.StartTime >= #FromDate
)
OR (
customerAppointments.StartTime >= DATEADD(day, -#maxAge, #CurrentDate)
)
)
UNION
SELECT
''Accident'' AS type
, ''Accident'' AS subtype
, ''Accident'' AS categoryType
, customerAccident.accident AS ''guid''
, customerAccident.accidentDate AS ActionDate
, ISNULL((SELECT name FROM userTable WHERE customerAccident.lastupdatedbyuser = userTable.guid),''system'') AS ''By''
, '''' as ''Improvement''
, customerAccident.accidentRef
+ '' - '' +
CASE
WHEN customerAccident.personalInjury = 1 THEN
''Injury''
WHEN customerAccident.nearMiss = 1 THEN
''Near miss''
WHEN customerAccident.propertyDamage = 1 THEN
''Property damage''
WHEN customerAccident.risk = 1 THEN
''Risk''
ELSE
''Other''
END AS ''action''
, CAST(customerAccident.injuryNature AS VARCHAR(4096)) AS ''text''
, customerAccident.timestamp
, 0
, 0 as ''hasattachment''
, '''' As ''hasBeenLookedAt''
, '''' AS ''IsAvailable''
, ''0'' AS sourceSystem
, '''' AS Categoryids
, '''' AS Duration
FROM
customerAccident
WHERE
customerAccident.customer = #customer
AND (
(
#maxAge = 0 AND customerAccident.accidentDate >= #FromDate
)
OR (
customerAccident.accidentDate >= DATEADD(day, -#maxAge, #CurrentDate)
)
)
UNION
SELECT
''Incident'' AS type
, ''Incident'' AS subtype
, ''Incident'' AS categoryType
, customerIncident.incident AS ''guid''
, customerIncident.incidentDate AS ActionDate
, ISNULL((SELECT name FROM userTable WHERE customerIncident.lastupdatedbyuser = userTable.guid),''system'') AS ''By''
, '''' AS ''Improvement''
, customerIncident.incidentRef + '' - '' + customerIncident.intensity AS ''action''
, CAST(customerIncident.narrative AS VARCHAR(4096)) AS ''text''
, customerIncident.timestamp
, 0
, 0 AS ''hasattachment''
, '''' As ''hasBeenLookedAt''
, '''' AS ''IsAvailable''
, ''0'' AS sourceSystem
, '''' AS Categoryids
, '''' AS Duration
FROM
customerIncident
WHERE
customerIncident.person = #customer
AND (
(
#maxAge = 0 AND customerIncident.incidentDate >= #FromDate
)
OR (
customerIncident.incidentDate >= DATEADD(day, -#maxAge, #CurrentDate)
)
)
ORDER BY
ActionDate Desc
',N'#customer uniqueidentifier,#FromDate datetime,#FromTimeStamp varbinary(8),#filterText nvarchar(258),#completed int,#completedAndPaid int,#Void int,#Cancelled int,#report nvarchar(9),#CurrentDate datetime,#sign int,#authorised int,#maxAge int',#customer='C661135D-0331-4544-82A7-335C2E7D40AF',#FromDate='2014-10-30 00:00:00',#FromTimeStamp=0x0000000000000000,#filterText=N'%%',#completed=15,#completedAndPaid=18,#Void=17,#Cancelled=20,#report=N'Customer Support',#CurrentDate='2014-11-06 00:00:00',#sign=524,#authorised=21,#maxAge=0
The view is cv_customerDailyReport and the tables customerHistory have been indexed. We have run the execution plans and tried to put more indexes based on them but still we are experiencing slowness.
Any help would be much appreciated.

how to include the parameter name as the name of a column in sql

I have a stored procedure that looks something like this :
CREATE PROCEDURE [dbo].[spRS_Get]
#Year Varchar(20),
#Month Varchar(20)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Paramdate datetime;
DECLARE #ParamYear varchar(4);
DECLARE #ParamMonth varchar(2);
DECLARE #Concatt varchar(10);
SET #ParamYear = #Year;
SET #ParamMonth = #Month;
SET #Concatt = #ParamMonth + '-' + '01' + '-' + #ParamYear;
SET #Paramdate = CONVERT(datetime, #Concatt);
SELECT Item
,SUM(CASE WHEN [MONTH] = month(#ParamDate) THEN Sales END) AS month(#ParamDate)
,SUM(CASE WHEN [MONTH] = month(#ParamDate) - 1 THEN Sales END) AS month(#ParamDate) - 1,
,SUM(CASE WHEN [MONTH] = month(#ParamDate) THEN Sales END) - SUM(CASE WHEN [MONTH] = month(#ParamDate) - 1 THEN Sales END) AS month(#ParamDate) - month(#ParamDate) - 1
FROM ABC
GROUP BY Item
In the above query , the part after the AS causes the error.
I want to use the parameter name as the name of the column , but it gives me an error. Is there a way I can use
the parameter name as the name of the month ?
You can only do that by building the select statement as a string and then executing it using the sp_executesql command.
So you'd get something like this:
declare #month0 varchar(2) = cast(month(#paramdate) as varchar(2));
declare #month1 varchar(2) = cast((month(#ParamDate) - 1) as varchar(2));
declare #month2 varchar(2) =
cast((month(#ParamDate) - month(#ParamDate) - 1) as varchar(2));
declare s nvarchar(1024) =
'SELECT Item
, SUM(CASE WHEN [MONTH] = month(#d) THEN Sales END)
AS ''' + #month0 +
''' , SUM(CASE WHEN [MONTH] = month(#d) - 1 THEN Sales END)
AS ''' + #month1 +
''' , SUM(CASE WHEN [MONTH] = month(#d) THEN Sales END) -
SUM(CASE WHEN [MONTH] = month(#d) - 1 THEN Sales END)
AS ''' + #month2 +
''' FROM ABC GROUP BY Item';
EXEC sp_executesql #s, N'#d DATETIME', #ParamDate;

Resources