Related
Can someone help me to optimise this SP as it takes more than 3 minutes to run and then it gives Timeout error. "Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding." I am a beginner and would like to optimise the below SP because it takes forever to give results and it also gives timeout error. I tried putting indexing to temp tables but unsuccessful. Help !!!!
ALTER PROCEDURE GetCompanyByCandidatetest
#USER_ID VARCHAR(50) = NULL
AS
BEGIN
declare #statenew varchar(1000) = Null
declare #countnew varchar(1000) = Null
declare #STRSQLNew varchar(max)
declare #STRSQL4 varchar(max)
declare #state1 varchar(1000) = Null ,#ind varchar(1000) = Null,#Distinct varchar(1000) = Null,#Dist1 varchar(1000) = Null,
#EQuit_ID varchar(1000) = Null,#Degree_ID varchar(100) = Null,#Isguest varchar(100) = Null,#verified varchar(100) = Null,
#keyword varchar(100) = Null,#workexperience varchar(100) = Null,#prefcity varchar(100) = Null,#addcity varchar(100) = Null,
#Key_skill varchar(100) = Null,#CURRENT_DEPARTMENT varchar(100),#PREF_DEPARTMENT varchar(100),#CURRENT_DESIGNATION varchar(100),#PREF_DESIGNATION varchar(100),#indcurr varchar(100)
select #Isguest = isnull(guest_login,0), #verified = isnull(VERIFIED,0) from mtb_frinds where user_id = #USER_ID
select #statenew = isnull(PREF_STATE,''),#state1 = isnull(ADD_STATE,''),#Distinct = isnull(PREF_DISTRICT,''),#Distinct1 = isnull(add_dist,''),
#ind = isnull(PREF_INDUSTRY,''),#indcurr=isnull(CURRENT_INDUSTRY,'') ,#EQuit_ID = isnull(EQ_ID,'') ,#keyword=isnull(key_word,'') ,#workexperience=isnull(WORK_EXPYEARS,''),#CURRENT_DEPARTMENT=isnull(CURRENT_DEPARTMENT,''), #PREF_DEPARTMENT=isnull(PREF_DEPARTMENT,''),
#prefcity=isnull(PREF_CITY,'') ,#addcity=ADD_CITY,#Key_skill=isnull(Key_skill,''),#CURRENT_DESIGNATION=isnull(CURRENT_DESIGNATION,''),#PREF_DESIGNATION=isnull(PREF_DESIGNATION,'')
from mtb_frinds where USER_ID = #USER_ID
if(#statenew!='' and #Key_skill !='' and #state1 !='' and #keyword !='' )
begin
print 'ind' +#ind
print '#indcurr' +#indcurr
print '#PREF_DEPARTMENT'+ #PREF_DEPARTMENT
print '#CURRENT_DEPARTMENT'+#CURRENT_DEPARTMENT
print '#keyword'+ #keyword
set #STRSQLNew='
select ej_id, EQ_ID, JOB_STATUS ,job_desc,
active, USER_ID, JOB_TITLE, CREATED_ON,
REQUIRED_MP, WORK_EXPYEARS, SALARY, IND_ID,
Key_skill, STATE_ID, DIST_ID, LOCALITY_ID,
DEPT_ID,1 as Priority, EXPIRATION_DATE
into #dummy from mtb_jobs Ek
'
IF #EQuit_ID IS NOT NULL AND #EQuit_ID != ''
BEGIN
print 1
SET #STRSQLNew = #STRSQLNew + ' CROSS APPLY dbo.Split(EQ_ID,'','') AS A
CROSS APPLY dbo.Split('''+#EQuit_ID+''','','') AS B'
set #STRSQL4 ='(((A.items = B.items) or '
END
IF #keyword IS NOT NULL AND #keyword != ''
BEGIN
print 2
SET #STRSQLNew = #STRSQLNew + ' CROSS APPLY dbo.Split(keywords,'','') AS e
CROSS APPLY dbo.Split('''+#keyword+''','','') AS f'
set #STRSQL4 =#STRSQL4+'(e.items =f.items)) and '
END
IF #statenew IS NOT NULL AND #statenew != ''
BEGIN
print 3
SET #STRSQLNew = #STRSQLNew + ' CROSS APPLY dbo.Split(STATE_ID,'','') AS i
CROSS APPLY dbo.Split('''+#statenew+''','','') AS j'
set #STRSQL4 = #STRSQL4+'((i.items =j.items) '
END
IF #state1 IS NOT NULL AND #state1 != ''
BEGIN
print 4
SET #STRSQLNew = #STRSQLNew + ' CROSS APPLY dbo.Split(STATE_ID,'','') AS k
CROSS APPLY dbo.Split('''+#state1+''','','') AS l'
set #STRSQL4 =#STRSQL4+' or (k.items =l.items)) and '
END
IF #Key_skill IS NOT NULL AND #Key_skill != ''
BEGIN
print 5
SET #STRSQLNew = #STRSQLNew + ' CROSS APPLY dbo.Split(Key_skill,'','') AS g
CROSS APPLY dbo.Split('''+#Key_skill+''','','') AS h'
set #STRSQL4 =#STRSQL4+' ((g.items =h.items) or
'
END
set #STRSQLNew = #STRSQLNew+ ' where '+ #STRSQL4 +'(DEPT_ID in (select items from dbo.split('''+#CURRENT_DEPARTMENT+''','','')) or DEPT_ID in (select items from dbo.split('''+#PREF_DEPARTMENT+''','','')))))
or(e.items =f.items and ((k.items =l.items) or (i.items =j.items) ))
'
set #STRSQLNew =#STRSQLNew+ ' select * into #temp from ( select max(ej_id) as ej_id , max(EQ_ID) as EQ_ID, max(JOB_STATUS) as JOB_STATUS , max(job_desc) as job_desc,max(active) as active, max(USER_ID) as USER_ID ,max(JOB_TITLE) as JOB_TITLE ,max(CREATED_ON) as CREATED_ON ,max(REQUIRED_MP) as REQUIRED_MP ,max(WORK_EXPYEARS) as WORK_EXPYEARS ,
max(SALARY) as SALARY ,max(IND_ID) as IND_ID ,max(Key_skill) as Key_skill , max(STATE_ID) as STATE_ID ,max(DIST_ID) as DIST_ID,max(LOCALITY_ID) as LOCALITY_ID ,max(DEPT_ID) as DEPT_ID,2 as Priority,max(EXPIRATION_DATE) as EXPIRATION_DATE from #dummy where EXPIRATION_DATE >0 group by ej_id
) as x '
set #STRSQLNew =#STRSQLNew+' select * into #Temp2 from
(
select a.ej_id, isnull(a.JOB_TITLE,'''') as JOB_TITLE, isnull(b.ENT_NAME,'''') as ENT_NAME, CASE
WHEN DATEDIFF(SECOND, a.CREATED_ON, GETDATE()) < 60 THEN ''Just Posted''
WHEN DATEDIFF(MINUTE, a.CREATED_ON, GETDATE()) < 60 THEN CAST(DATEDIFF(MINUTE, a.CREATED_ON, GETDATE()) AS VARCHAR(10)) + '' Minutes ago''
WHEN DATEDIFF(MINUTE, a.CREATED_ON, GETDATE()) < 24 * 60 THEN CAST(FLOOR(DATEDIFF(MINUTE, a.CREATED_ON, GETDATE())/60) AS VARCHAR(10)) + '' Hours ago''
ELSE CAST(FLOOR(DATEDIFF(HOUR, a.CREATED_ON, GETDATE())/24) AS VARCHAR(10)) + ''Days ago''
END AS POSTED_ON,a.REQUIRED_MP,''1'' as Issuitable,a.job_desc, a.created_on,DATEDIFF(DAY,GETDATE(),a.EXPIRATION_DATE) as EXPIRATION_DATE
,isnull('''+#Isguest+''',''0'') as Isguest,isnull('''+#verified+''',''0'') as Isverified
,isnull(cnt,0) as Isapplied,substring(
(
Select distinct '', ''+ ST1.StateName AS [text()]
From MTB_STATESNEW ST1
Where ST1.StateId in (select items from dbo.split (a.state_id,'',''))
For XML PATH ('''')
), 2, 1000000) [StateName],
substring(
(
Select distinct '', ''+ min(convert(varchar(1000),ST1.MIN_EXP)) AS [text()]
From dbo.MTB_WORKEXP ST1
Where ST1.EXP_ID in (select items from dbo.split (a.WORK_EXPYEARS,'',''))
For XML PATH ('''')
), 2, 1000000) [min_exp],
substring(
(
Select distinct '',''+ max(convert(varchar(1000),ST1.MAX_EXP)) AS [text()]
From dbo.MTB_WORKEXP ST1
Where ST1.EXP_ID in (select items from dbo.split (a.WORK_EXPYEARS,'',''))
For XML PATH ('''')
), 2, 1000000) [max_exp],
substring(
(
Select distinct '', ''+ min(convert(varchar(1000),ST1.SR_MIN)) AS [text()]
From dbo.MTB_SALARYRANGE ST1
Where ST1.SR_ID in (select min(items) from dbo.split (a.SALARY,'',''))
For XML PATH ('''')
), 2, 1000000) [min_Salary],
substring(
(
Select distinct '',''+ max(convert(varchar(1000),ST1.sr_max)) AS [text()]
From dbo.MTB_SALARYRANGE ST1
Where ST1.SR_ID in (select items from dbo.split (a.SALARY,'',''))
For XML PATH ('''')
), 2, 1000000) [max_Salary],
substring(
(
Select distinct '',''+ (convert(varchar(1000),ST1.KEY_SKILL)) AS [text()]
From MTB_KEYSKILL ST1
Where ST1.KEYSKILL_ID in (select items from dbo.split (a.Key_skill,'',''))
For XML PATH ('''')
), 2, 1000000) [KEY_SKILL]
,
substring (
(Select distinct '',''+ (convert(varchar(1000),ST1.KEYWORDS)) AS [text()]
From mtb_keywords ST1 where st1.KEYWORD_ID in ( select items from dbo.split('''+#keyword+''','',''))
For XML PATH ('''')
), 2, 1000000) [KEY_Word],
substring (
(Select distinct '',''+ (convert(varchar(1000),ST1.DIST_NAME)) AS [text()]
From MTB_DISTSNEW ST1 where st1.DIST_ID in ( select items from dbo.split(a.DIST_ID,'',''))
For XML PATH ('''')
), 2, 1000000) [dist_name],
substring(
(select distinct '',''+(convert(varchar(1000),ST1.EQ_NAME)) as [text()]
from MTB_EDUQUALIFICATIONS ST1 where st1.EQ_ID in (select items from dbo.split(a.EQ_ID,'',''))
For XML PATH('''')
),2,1000000) [EQ_Name],
substring(
(select distinct '',''+(convert(varchar(1000),ST1.IND_NAME)) as [text()]
from mtb_industry ST1 where st1.ind_id in (select items from dbo.split(a.ind_id,'',''))
For XML PATH('''')
),2,1000000) [IND_NAME]
from #temp as a inner join MTB_ENTERPRISES as b on a.user_id = b.user_id
left join (select count (ej_id) as cnt,ej_id from TTB_JOBAPPLICATIONS where USER_ID = '''+#USER_ID+''' group by EJ_ID) as ER on ER.EJ_ID = a.EJ_ID
where( a.JOB_STATUS = 1 and a.active = 1 )
) as x'
set #STRSQLNew =#STRSQLNew+' SELECT *,isnull(min_exp,'''') +''-''+ isnull(max_exp,'''') as WORK_EXP,isnull(min_Salary,'''') +''-''+ isnull(max_salary,'''') as Salary FROM #Temp2 '
print #STRSQLNew
exec (#STRSQLNew)
select 1 as ispara1, 'Sucess' as Msg ,1 as n
end
else
begin
select top 0* from MTB_ENTERPRISES
select 0 as ispara2, 0 as n,'Some fields are Incomplete' as Msg
end
END
Error:- Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
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;
what were the last few queries ran on SQL Server and with client name (system name) ?
i am running this query in server side
below query getting queries
SELECT deqs.last_execution_time AS [Time], dest.TEXT AS [Query]
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
ORDER BY deqs.last_execution_time DESC
how can i get system name
for e.g
time | query | System Name
You could check the sp_who and sp_who2 text.
create procedure sys.sp_who2 --- 1995/11/03 10:16
#loginame sysname = NULL
as
set nocount on
declare
#retcode int
declare
#sidlow varbinary(85)
,#sidhigh varbinary(85)
,#sid1 varbinary(85)
,#spidlow int
,#spidhigh int
declare
#charMaxLenLoginName varchar(6)
,#charMaxLenDBName varchar(6)
,#charMaxLenCPUTime varchar(10)
,#charMaxLenDiskIO varchar(10)
,#charMaxLenHostName varchar(10)
,#charMaxLenProgramName varchar(10)
,#charMaxLenLastBatch varchar(10)
,#charMaxLenCommand varchar(10)
declare
#charsidlow varchar(85)
,#charsidhigh varchar(85)
,#charspidlow varchar(11)
,#charspidhigh varchar(11)
-- defaults
select #retcode = 0 -- 0=good ,1=bad.
select #sidlow = convert(varbinary(85), (replicate(char(0), 85)))
select #sidhigh = convert(varbinary(85), (replicate(char(1), 85)))
select
#spidlow = 0
,#spidhigh = 32767
--------------------------------------------------------------
IF (#loginame IS NULL) --Simple default to all LoginNames.
GOTO LABEL_17PARM1EDITED
-- select #sid1 = suser_sid(#loginame)
select #sid1 = null
if exists(select * from sys.syslogins where loginname = #loginame)
select #sid1 = sid from sys.syslogins where loginname = #loginame
IF (#sid1 IS NOT NULL) --Parm is a recognized login name.
begin
select #sidlow = suser_sid(#loginame)
,#sidhigh = suser_sid(#loginame)
GOTO LABEL_17PARM1EDITED
end
--------
IF (lower(#loginame collate Latin1_General_CI_AS) IN ('active')) --Special action, not sleeping.
begin
select #loginame = lower(#loginame collate Latin1_General_CI_AS)
GOTO LABEL_17PARM1EDITED
end
--------
IF (patindex ('%[^0-9]%' , isnull(#loginame,'z')) = 0) --Is a number.
begin
select
#spidlow = convert(int, #loginame)
,#spidhigh = convert(int, #loginame)
GOTO LABEL_17PARM1EDITED
end
--------
raiserror(15007,-1,-1,#loginame)
select #retcode = 1
GOTO LABEL_86RETURN
LABEL_17PARM1EDITED:
-------------------- Capture consistent sysprocesses. -------------------
select
spid
,status
,sid
,hostname
,program_name
,cmd
,cpu
,physical_io
,blocked
,dbid
,convert(sysname, rtrim(loginame))
as loginname
,spid as 'spid_sort'
, substring( convert(varchar,last_batch,111) ,6 ,5 ) + ' '
+ substring( convert(varchar,last_batch,113) ,13 ,8 )
as 'last_batch_char'
,request_id
into #tb1_sysprocesses
from sys.sysprocesses_ex with (nolock)
if ##error <> 0
begin
select #retcode = ##error
GOTO LABEL_86RETURN
end
--------Screen out any rows?
if (#loginame in ('active'))
delete #tb1_sysprocesses
where lower(status) = 'sleeping'
and upper(cmd) in (
'AWAITING COMMAND'
,'LAZY WRITER'
,'CHECKPOINT SLEEP'
)
and blocked = 0
--------Prepare to dynamically optimize column widths.
select
#charsidlow = convert(varchar(85),#sidlow)
,#charsidhigh = convert(varchar(85),#sidhigh)
,#charspidlow = convert(varchar,#spidlow)
,#charspidhigh = convert(varchar,#spidhigh)
select
#charMaxLenLoginName =
convert( varchar
,isnull( max( datalength(loginname)) ,5)
)
,#charMaxLenDBName =
convert( varchar
,isnull( max( datalength( rtrim(convert(varchar(128),db_name(dbid))))) ,6)
)
,#charMaxLenCPUTime =
convert( varchar
,isnull( max( datalength( rtrim(convert(varchar(128),cpu)))) ,7)
)
,#charMaxLenDiskIO =
convert( varchar
,isnull( max( datalength( rtrim(convert(varchar(128),physical_io)))) ,6)
)
,#charMaxLenCommand =
convert( varchar
,isnull( max( datalength( rtrim(convert(varchar(128),cmd)))) ,7)
)
,#charMaxLenHostName =
convert( varchar
,isnull( max( datalength( rtrim(convert(varchar(128),hostname)))) ,8)
)
,#charMaxLenProgramName =
convert( varchar
,isnull( max( datalength( rtrim(convert(varchar(128),program_name)))) ,11)
)
,#charMaxLenLastBatch =
convert( varchar
,isnull( max( datalength( rtrim(convert(varchar(128),last_batch_char)))) ,9)
)
from
#tb1_sysprocesses
where
spid >= #spidlow
and spid <= #spidhigh
--------Output the report.
EXEC(
'
SET nocount off
SELECT
SPID = convert(char(5),spid)
,Status =
CASE lower(status)
When ''sleeping'' Then lower(status)
Else upper(status)
END
,Login = substring(loginname,1,' + #charMaxLenLoginName + ')
,HostName =
CASE hostname
When Null Then '' .''
When '' '' Then '' .''
Else substring(hostname,1,' + #charMaxLenHostName + ')
END
,BlkBy =
CASE isnull(convert(char(5),blocked),''0'')
When ''0'' Then '' .''
Else isnull(convert(char(5),blocked),''0'')
END
,DBName = substring(case when dbid = 0 then null when dbid <> 0 then db_name(dbid) end,1,' + #charMaxLenDBName + ')
,Command = substring(cmd,1,' + #charMaxLenCommand + ')
,CPUTime = substring(convert(varchar,cpu),1,' + #charMaxLenCPUTime + ')
,DiskIO = substring(convert(varchar,physical_io),1,' + #charMaxLenDiskIO + ')
,LastBatch = substring(last_batch_char,1,' + #charMaxLenLastBatch + ')
,ProgramName = substring(program_name,1,' + #charMaxLenProgramName + ')
,SPID = convert(char(5),spid) --Handy extra for right-scrolling users.
,REQUESTID = convert(char(5),request_id)
from
#tb1_sysprocesses --Usually DB qualification is needed in exec().
where
spid >= ' + #charspidlow + '
and spid <= ' + #charspidhigh + '
-- (Seems always auto sorted.) order by spid_sort
SET nocount on
'
)
LABEL_86RETURN:
if (object_id('tempdb..#tb1_sysprocesses') is not null)
drop table #tb1_sysprocesses
return #retcode -- sp_who2
Hope this helps.
The below query should help you:
SELECT conn.session_id, sson.host_name, sson.login_name,
sqltxt.text, sson.login_time, sson.status
FROM sys.dm_exec_connections conn
INNER JOIN sys.dm_exec_sessions sson
ON conn.session_id = sson.session_id
CROSS APPLY sys.dm_exec_sql_text(most_recent_sql_handle) AS sqltxt
ORDER BY conn.session_id desc
Source: http://www.sqlservercurry.com/2011/12/last-run-query-in-sql-server.html
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.
I have a stored procedure, its really simple, just one select statement, however the where clause changes based on the parameters.
I am using if else statement and wrote out the select 4 times, is there a better way to simplify this stored procedure?
IF #Status > 0
BEGIN
IF #Group = ''
BEGIN
SELECT *
FROM ( SELECT tbl.* ,
ROW_NUMBER() OVER ( ORDER BY tbl.NDB_No ) rownum
FROM dbo.FoodAbbrev AS tbl
WHERE Status = #Status
) seq
WHERE seq.rownum BETWEEN #X AND #Y
ORDER BY seq.rownum
END
ELSE
BEGIN
SELECT *
FROM ( SELECT tbl.* ,
ROW_NUMBER() OVER ( ORDER BY tbl.NDB_No ) rownum
FROM dbo.FoodAbbrev AS tbl
WHERE Status = #Status
AND GroupCd = #Group
) seq
WHERE seq.rownum BETWEEN #X AND #Y
ORDER BY seq.rownum
END
END
ELSE
BEGIN
IF #Group = ''
BEGIN
SELECT *
FROM ( SELECT tbl.* ,
ROW_NUMBER() OVER ( ORDER BY tbl.NDB_No ) rownum
FROM dbo.FoodAbbrev AS tbl
) seq
WHERE seq.rownum BETWEEN #X AND #Y
ORDER BY seq.rownum
END
ELSE
BEGIN
SELECT *
FROM ( SELECT tbl.* ,
ROW_NUMBER() OVER ( ORDER BY tbl.NDB_No ) rownum
FROM dbo.FoodAbbrev AS tbl
WHERE GroupCd = #Group
) seq
WHERE seq.rownum BETWEEN #X AND #Y
ORDER BY seq.rownum
END
END
END
Replace all these IF statements with the following one SELECT statments with optional parameters:
SELECT *
FROM ( SELECT tbl.* ,
ROW_NUMBER() OVER ( ORDER BY tbl.NDB_No ) rownum
FROM dbo.FoodAbbrev AS tbl
WHERE 1 = 1
AND (#Group IS NULL OR GroupCd = #Group)
AND (#Status IS NULL OR Status = #Status)
) seq
WHERE seq.rownum BETWEEN #X AND #Y
ORDER BY seq.rownum
SELECT *
FROM ( SELECT tbl.* ,
ROW_NUMBER() OVER ( ORDER BY tbl.NDB_No ) rownum
FROM dbo.FoodAbbrev AS tbl
WHERE ISNULL(Status,0) = CASE WHEN #Status > 0 THEN #Status ELSE ISNULL(Status,0) END
AND ISNULL(GroupCd, '') = CASE WHEN #Group = '' THEN ISNULL(GroupCd, '') ELSE #Group END
) seq
WHERE seq.rownum BETWEEN #X AND #Y
ORDER BY seq.rownum