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.
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.
Using SQL Server, I need to get a column count that has -1, 0, 1, 2 for its values for each row. There are different number of columns per table (one table has 55 fields)
-1 value = no answer or unknown (unknown_count)
0 value = ok (ok_count)
1 value = bad (bad_count)
2 value = not applicable (na_count)
row 1 looks like this
rowid name field_1 field_2 field_3 field_4
1 line_1 -1 1 2 1
2 line_2 2 1 -1 0
etc...
Results i would like to see
rowid na_count ok_count bad_count unknown_count
1 1 0 2 1
2 1 1 1 1
Extra credit question.... i need to get a count of all the fields that are used to build the counts (so i can give a percentile report)
You need a combination of UNPIVOT and some aggregation. Unpivot the data to a more sensible form, and then group by rowid summing up the various values:
with data AS
(
select
rowid,
field,
value
from
( SELECT rowid, field_1,field_2,field_3,field_4
FROM MyTable) p
UNPIVOT
( value FOR field IN (field_1,field_2,field_3,field_4) ) as unpvt
)
SELECT
rowid,
SUM(CASE WHEN value = 2 THEN 1 ELSE 0 END) AS na_count,
SUM(CASE WHEN value = 0 THEN 1 ELSE 0 END) AS ok_count,
SUM(CASE WHEN value = 1 THEN 1 ELSE 0 END) AS bad_count,
SUM(CASE WHEN value = -1 THEN 1 ELSE 0 END) AS unknown_count
from data
group by rowId
Live example: http://www.sqlfiddle.com/#!6/b702c/1
Building on the answer by Jamiec and some code I've used before; If you don't want to type in all the column names in the query you can use dynamic sql to build the query like this:
declare #tab nvarchar(max)
set #tab = N'your_table' -- change to your table name
declare #cols nvarchar(max)
select #cols = coalesce(#cols+N',', N'') + quotename(c.name) from syscolumns c
inner join sysobjects o on c.id = o.id and o.xtype = 'u'
where o.name = #tab
and c.name not in ('rowid', 'name') -- exclude the columns that don't hold data values
order by c.colid
declare #sql nvarchar(max)
select #sql = N'
select
rowid,
sum(case when val = 2 then 1 else 0 end) as ''na_count'',
sum(case when val = 0 then 1 else 0 end) as ''ok_count'',
sum(case when val = 1 then 1 else 0 end) as ''bad_count'',
sum(case when val = -1 then 1 else 0 end) as ''unknown_count'',
count(*) as column_count
from (select rowid, ' + #cols + N' from ' + #tab + N') as src
unpivot (val for col in (' + #cols + N')) as unpvt
group by rowid'
exec sp_executesql #sql
I think it will be more effective to sum up all the columns in a dynamical script, rather than to use unpivot. On one million rows i get 16% vs 84% relative to the batch in the execution plan (this code´s output #query vs the unpivot code).
You can use the same logic to get the percentages of each column. Please let me know if you want me to provide you with code for that as well.
--DROP TABLE TMP_Test
CREATE TABLE TMP_Test
(
rowid INT PRIMARY KEY IDENTITY(1,1)
, name varchar(10)
, field_1 INT
, field_2 INT
, field_3 INT
, field_4 INT
)
INSERT INTO TMP_Test
SELECT name = 'line_1', field_1 = -1, field_2=1, field_3=2, field_4=1
UNION ALL
SELECT name = 'line_2', field_1 = 2, field_2=1, field_3=-1, field_4= 0
/*
WHILE((SELECT COUNT(*) FROM TMP_Test) < 1000000)
BEGIN
INSERT INTO TMP_Test
SELECT name, field_1, field_2, field_3, field_4 FROM TMP_Test
END
*/
GO
DECLARE #query VARCHAR(MAX) = '';
DECLARE #schema VARCHAR(128) = 'dbo';
DECLARE #table VARCHAR(128) = 'TMP_Test';
DECLARE #na_count VARCHAR(max) = '';
DECLARE #ok_count VARCHAR(max) = '';
DECLARE #bad_count VARCHAR(max) = '';
DECLARE #unknown_count VARCHAR(max) = '';
SELECT
#na_count = #na_count + IIF(#na_count = '', '', ' + ') + 'IIF(' + COLUMN_NAME + ' = 2, 1, 0)'
, #ok_count = #ok_count + IIF(#ok_count = '', '', ' + ') + 'IIF(' + COLUMN_NAME + ' = 0, 1, 0)'
, #bad_count = #bad_count + IIF(#bad_count = '', '', ' + ') + 'IIF(' + COLUMN_NAME + ' = 1, 1, 0)'
, #unknown_count = #unknown_count + IIF(#unknown_count = '', '', ' + ') + 'IIF(' + COLUMN_NAME + ' = -1, 1, 0)'
FROM INFORMATION_SCHEMA.COLUMNS WHERE
TABLE_SCHEMA = #schema
AND TABLE_NAME = #table
AND COLUMN_NAME NOT IN ('rowid', 'name')
ORDER BY ORDINAL_POSITION;
SET #query = '
SELECT
rowid
, na_count = ' + #na_count + '
, ok_count = ' + #ok_count + '
, bad_count = ' + #bad_count + '
, unknown_count = ' + #unknown_count + '
FROM [' + #schema + '].[' + #table + ']';
PRINT(#query);
EXEC(#query);
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]'
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
DECLARE #temp TABLE
(
iLeadID INT ,
Title VARCHAR(MAX) ,
AlertDate DATETIME
)
DECLARE #iLeadID INT
DECLARE #getiLeadID CURSOR
SET
#getiLeadID = CURSOR FOR
SELECT iLeadID FROM LeadsContracts
OPEN #getiLeadID
FETCH NEXT FROM #getiLeadID INTO #iLeadID
WHILE ##FETCH_STATUS = 0
BEGIN
INSERT INTO #temp
SELECT #iLeadID ,
'Disclosure' ,
CONVERT(VARCHAR, dtDisclosure, 101) 'Date'
FROM LeadsContracts
WHERE iLeadID = #iLeadID
AND dtDisclosure IS NOT NULL
INSERT INTO #temp
SELECT #iLeadID ,
'Due Diligence' ,
CONVERT(VARCHAR, dtDueDiligence, 101) 'Date'
FROM LeadsContracts
WHERE iLeadID = #iLeadID
AND dtDueDiligence IS NOT NULL
INSERT INTO #temp
SELECT #iLeadID ,
'Finance Appraisals' ,
CONVERT(VARCHAR, dtFinanceAppraisals, 101) 'Date'
FROM LeadsContracts
WHERE iLeadID = #iLeadID
AND dtFinanceAppraisals IS NOT NULL
INSERT INTO #temp
SELECT #iLeadID ,
sFreeTextCustom1 ,
CONVERT(VARCHAR, dtFreeTextDate1, 101) 'Date'
FROM LeadsContracts
WHERE iLeadID = #iLeadID
AND dtFreeTextDate1 IS NOT NULL
INSERT INTO #temp
SELECT #iLeadID ,
sFreeTextCustom2 ,
CONVERT(VARCHAR, dtFreeTextDate2, 101) 'Date'
FROM LeadsContracts
WHERE iLeadID = #iLeadID
AND dtFreeTextDate2 IS NOT NULL
FETCH NEXT FROM #getiLeadID INTO #iLeadID
END
CLOSE #getiLeadID
DEALLOCATE #getiLeadID
SELECT * ,
( CASE WHEN 1 = 1
THEN ( SELECT TOP 1
sEmail
FROM UserAccount objUA
WHERE EXISTS ( SELECT iUserID
FROM GroupAgent
WHERE iUserID = objUA.iUserID
AND iGroupID = t1.GroupID
AND btAdminFlg = ( (1) ) )
)
ELSE ''
END ) AS AdminEmail
FROM ( SELECT * ,
CASE WHEN 1 = 1
THEN ( SELECT TOP 1
sFirstName + ' ' + sLastName
FROM Lead
WHERE iLeadID = objTemp.iLeadID
)
ELSE ''
END AS LeadName ,
CASE WHEN 1 = 1
THEN ( SELECT TOP 1
sEmail
FROM Lead
WHERE iLeadID = objTemp.iLeadID
)
ELSE ''
END AS LeadEmail ,
CASE WHEN 1 = 1
THEN ( SELECT TOP 1
iUserID
FROM AssignLeadUser
WHERE iLeadID = objTemp.iLeadID
)
ELSE ''
END AS AgentID ,
CASE WHEN 1 = 1
THEN ( SELECT TOP 1
sFirstName + ' ' + sLastName
FROM UserAccount
WHERE iUserID = ( SELECT
iUserID
FROM AssignLeadUser
WHERE iLeadID = objTemp.iLeadID
)
)
ELSE ''
END AS AgentName ,
CASE WHEN 1 = 1
THEN ( SELECT TOP 1
sEmail
FROM UserAccount
WHERE iUserID = ( SELECT
iUserID
FROM AssignLeadUser
WHERE iLeadID = objTemp.iLeadID
)
)
ELSE ''
END AS AgentEmail ,
CASE WHEN 1 = 1
THEN ( SELECT TOP 1
iGroupID
FROM AssignLeadUser
WHERE iLeadID = objTemp.iLeadID
)
ELSE ''
END AS GroupID ,
CASE WHEN 1 = 1
THEN ( SELECT TOP 1
sName
FROM [Group]
WHERE iGroupID = ( SELECT
iGroupID
FROM AssignLeadUser
WHERE
iLeadID = objTemp.iLeadID
)
)
ELSE ''
END AS GroupName
FROM #temp objTemp
) AS t1
ORDER BY AlertDate ASC
it gives me an output of 2013-04-04 00:00:00.000 in the AlertDate column
I want to get only the date (no time) like this: 2013-04-04" in the AlterDate column.
Could anybody please help me to advice some query or update my code?
Thanks in advance
You can use the date type instead of datetime
declare #temp Table
(
iLeadID int,
Title varchar(Max),
AlertDate date
)
You have AlterDate typed as a DATETIME. If you only want to store the date, use a DATE data type. An added benefit of doing this is that the DATE data type only takes 3 bytes instead of the DATETIME's 8 bytes.
If you subsequently need to turn AlterDate back into a DATETIME, it will use the midnight value that you're currently seeing.