Optimise a Stored procedure in SQL? Facing Error - sql-server

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.

Related

Pivot with Group by on SQL

I'm create sql syntax which create pivot Group By Product based on Category
CREATE TABLE #Product ( Product varchar(10),Category varchar(10),Stock int)
INSERT INTO #Product Values ('Item A','CatA',10)
INSERT INTO #Product Values ('Item A','CatB',5)
INSERT INTO #Product Values ('Item B','CatA',3)
INSERT INTO #Product Values ('Item B','CatB',5)
INSERT INTO #Product Values ('Item B','CatC',7)
INSERT INTO #Product Values ('Item B','CatD',10)
SELECT *
FROM
(
SELECT Product,Category,Stock
FROM #Product A
) src
pivot
(
SUM(Stock)
for Category in ([CatA], [CatB], [CatC],[CatD])
) piv;
DROP TABLE #Product
Result of Query
Product CatA CatB CatC CatD
Item A 10 5 NULL NULL
Item B 3 5 7 10
Result trying to achieve is
Product Cat1 Stock1 Cat2 Stock2 Cat3 Stock3 Cat4 Stock4
Item A CatA 10 CatB 5 CatC 0 CatD 0
Item B CatA 3 CatB 5 CatC 7 CatD 10
Thanks for the help
You need to create all combinations of Product and Category first. Then do a LEFT JOIN on #Product to get the Stock. Finally, use the result to pivot the data.
Since I'm not familiar with the PIVOT command, I used another technique called Dynamic Crosstab
DECLARE #sql NVARCHAR(MAX) = N'';
SELECT #sql =
'SELECT
Product' + CHAR(10);
SELECT #sql = #sql +
STUFF((
SELECT
' ,MAX(CASE WHEN RN = ' + CONVERT(VARCHAR(3), t.RN) + ' THEN Category END) AS ' + QUOTENAME('Cat' + CONVERT(VARCHAR(3), t.RN)) + CHAR(10) +
' ,MAX(CASE WHEN RN = ' + CONVERT(VARCHAR(3), t.RN) + ' THEN Stock END) AS ' + QUOTENAME('Stock' + CONVERT(VARCHAR(3), t.RN)) + CHAR(10)
FROM (
SELECT DISTINCT
RN = ROW_NUMBER() OVER(PARTITION BY Product ORDER BY(SELECT NULL))
FROM #Product
) t
FOR XML PATH('')
), 1, 1, ' ');
SELECT #sql = #sql +
'FROM(
SELECT
p1.Product,
p1.Category,
Stock = ISNULL(p2.Stock, 0),
RN = ROW_NUMBER() OVER(PARTITION BY p1.Product ORDER BY p1.Category)
FROM (
SELECT
t1.Product, t2.Category
FROM (
SELECT DISTINCT Product FROM #Product
) t1
CROSS JOIN (
SELECT DISTINCT Category FROM #Product
) t2
) p1
LEFT JOIN #Product p2
ON p1.Product = p2.Product
AND p1.Category = p2.Category
)t
GROUP BY Product;';
PRINT #sql;
EXEC sp_executesql #sql;
ONLINE DEMO

what were the last few queries ran on SQL Server ?

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

SQL: Msg 156, Level 15, State 1 :Incorrect syntax near the keyword 'END'

Ok i have 2 questions 1) I've googled that error(in title) but I cant seem to get it to help me, my proc:
CREATE PROCEDURE [dbo].[p_Target]
AS
BEGIN
SET NOCOUNT ON
CREATE TABLE #tmp1
(
AUD_ID BIGINT,
RowCounter BIGINT,
DistinctCounter BIGINT,
NACounter BIGINT,
Total BIGINT,
[Status] VARCHAR(MAX)
)
INSERT INTO #tmp1 EXEC [p_GetCompleteIncompleteNaOverviewSCORE]
DECLARE #Total AS INT
SELECT #Total = COUNT(*)
FROM (
SELECT CASE WHEN CONVERT(DATETIME,CONVERT(CHAR(10),DATEADD(DAY,0,t2.AUD_TargetDate), 101)) < CONVERT(DATETIME,CONVERT(CHAR(10),DATEADD(DAY,0,GETDATE()), 101))
THEN 'Over Due: '
ELSE 'On Time: ' END AS [Target Status]
FROM #tmp1 t1 INNER JOIN dbo.Audit t2
ON t1.AUD_ID = t2.AUD_ID
WHERE t1.[Status] = 'Open') DER
SELECT ([Target Status] + '' + CAST(COUNT(*) AS NVARCHAR(255)) + ' of ' + CAST(#Total AS NVARCHAR(255))) AS TargetStatus, (SELECT COUNT(*)) * 100 / (SELECT ([Target Status] + '' + CAST(COUNT(*) AS NVARCHAR(255))) AS [Count]
FROM (
SELECT CASE WHEN CONVERT(DATETIME,CONVERT(CHAR(10),DATEADD(DAY,0,t2.AUD_TargetDate), 101)) < CONVERT(DATETIME,CONVERT(CHAR(10),DATEADD(DAY,0,GETDATE()), 101))
THEN 'Over Due: '
ELSE 'On Time: ' END AS [Target Status]
FROM #tmp1 t1 INNER JOIN dbo.Audit t2
ON t1.AUD_ID = t2.AUD_ID
WHERE t1.[Status] = 'Open') DER
GROUP BY [Target Status]
END
GO
I've tied adding ) to NVARCHAR(255))) AS [Count] but still errors,
2)I need to get AS [Count] as a percentag, if anyone can help? That is my try code maybe i am on the right track.?
You're missing a close paren on your final subselect. Also, you're missing the 'S' in SET NOCOUNT. Updates below.
CREATE PROCEDURE [dbo].[p_Target]
AS
BEGIN
SET NOCOUNT ON
CREATE TABLE #tmp1
(
AUD_ID BIGINT,
RowCounter BIGINT,
DistinctCounter BIGINT,
NACounter BIGINT,
Total BIGINT,
[Status] VARCHAR(MAX)
)
INSERT INTO #tmp1 EXEC [p_GetCompleteIncompleteNaOverviewSCORE]
DECLARE #Total AS INT
SELECT #Total = COUNT(*)
FROM (
SELECT CASE WHEN CONVERT(DATETIME,CONVERT(CHAR(10),DATEADD(DAY,0,t2.AUD_TargetDate), 101)) < CONVERT(DATETIME,CONVERT(CHAR(10),DATEADD(DAY,0,GETDATE()), 101))
THEN 'Over Due: '
ELSE 'On Time: ' END AS [Target Status]
FROM #tmp1 t1 INNER JOIN dbo.Audit t2
ON t1.AUD_ID = t2.AUD_ID
WHERE t1.[Status] = 'Open') DER
SELECT ([Target Status] + '' + CAST(COUNT(*) AS NVARCHAR(255)) + ' of ' + CAST(#Total AS NVARCHAR(255))) AS TargetStatus, (SELECT COUNT(*)) * 100 / (SELECT ([Target Status] + '' + CAST(COUNT(*) AS NVARCHAR(255))) AS [Count]
FROM (
SELECT CASE WHEN CONVERT(DATETIME,CONVERT(CHAR(10),DATEADD(DAY,0,t2.AUD_TargetDate), 101)) < CONVERT(DATETIME,CONVERT(CHAR(10),DATEADD(DAY,0,GETDATE()), 101))
THEN 'Over Due: '
ELSE 'On Time: ' END AS [Target Status]
FROM #tmp1 t1 INNER JOIN dbo.Audit t2
ON t1.AUD_ID = t2.AUD_ID
WHERE t1.[Status] = 'Open') DER
GROUP BY [Target Status]
)
END
GO
Is it the missing 'S' on SET NOCOUNT ON after the initial begin perhaps?
It looks like your SELECT statement above your last last FROM statement has an un-closed parentheses. That would make the parser throw an error when it hits the END statement, since it still thinks it's working on the SELECT.
SELECT ([Target Status] + '' + CAST(COUNT(*) AS NVARCHAR(255)) + ' of ' + CAST(#Total AS NVARCHAR(255))) AS TargetStatus, (SELECT COUNT(*)) * 100 / (SELECT ([Target Status] + '' + CAST(COUNT(*) AS NVARCHAR(255))) AS [Count]
^
Whenever you get an incorrect Syntax error it's best to carefully go through your code and check that all statements are well formed and complete. Usually google can't help you, since it's very specific to your code. A good approach to finding the fault is to locate the point of the error (END in this case) and work backwards. The cause of the error may be quite far above the actual point that the error is thrown, but it will be somewhere above the error. And reading backwards can help you catch simple mistakes.
Create Table TblAccount (UserName nvarchar(20) Primary Key,UserPwd varchar(20) not null)
Declare #i int
Set #i=1
While #i<=10
I have one question
BEGIN
Insert INTO TblAccount Values('Seng Vitou'+CAST(#i AS VARCHar(2)),REVERSE('pwd'+CAST(#i as varchar(2))
SET #i=#i+1
End
Msg 156, Level 15, State 1, Line 11
Incorrect syntax near the keyword 'SET'.

How to compare two string elements in SQL Server

I have two strings in SQL Server.
For example:
declare #str1 as varchar(max)
declare #str2 as varchar(max)
set #str1 ='10:00am,2:00pm'
set #str2 = '10:00am,12:00pm,2:00pm,4:00pm,6:00pm,8:00pm'
and I want to compare the two strings and want to get those elements string from #str2 which are not in #str1.
That means the result should be :
#str3 = '12:00pm,4:00pm,6:00pm,8:00pm'
Try this :-
declare #str1 as varchar(max)
declare #str2 as varchar(max)
set #str1 ='10:00am,2:00pm'
set #str2 = '10:00am,12:00pm,2:00pm,4:00pm,6:00pm,8:00pm'
--the below 2 CTE's are used for splitting the string into different rows
;with cteStr1(str1) as
(
SELECT
RIGHT(LEFT(#str1,Number-1),
CHARINDEX(',',REVERSE(LEFT(','+#str1,Number-1)))) as str1
FROM
master..spt_values
WHERE
Type = 'P' AND Number BETWEEN 1 AND LEN(#str1)+1
AND
(SUBSTRING(#str1,Number,1) = ',' OR SUBSTRING(#str1,Number,1) = '')
),cteStr2(str2) as
(
SELECT
RIGHT(LEFT(#str2,Number-1),
CHARINDEX(',',REVERSE(LEFT(','+#str2,Number-1)))) as str2
FROM
master..spt_values
WHERE
Type = 'P' AND Number BETWEEN 1 AND LEN(#str2)+1
AND
(SUBSTRING(#str2,Number,1) = ',' OR SUBSTRING(#str2,Number,1) = '')
)
Select str2 from cteStr2
except
select str1 from cteStr1
Try this
DECLARE #str1 VARCHAR(MAX)
DECLARE #str2 VARCHAR(MAX)
SET #str1 ='10:00am,2:00pm'
SET #str2 = '10:00am,12:00pm,2:00pm,4:00pm,6:00pm,8:00pm'
SET #str1 = ',' + #str1 + ','
SET #str2 = ',' + #str2 + ','
DECLARE #name NVARCHAR(255)
DECLARE #pos INT
WHILE CHARINDEX(',', #str1) > 0
BEGIN
SELECT #pos = CHARINDEX(',', #str1)
SELECT #name = SUBSTRING(#str1, 1, #pos-1)
SELECT #str1 = SUBSTRING(#str1, #pos+1, LEN(#str1)-#pos)
IF #name <> ''
BEGIN
SET #str2 = REPLACE(#str2,','+#name,'')
END
END
SET #str2 = REPLACE(#str2,','+#name,'')
SELECT SUBSTRING(#str2, 2, LEN(#str2)-2) AS Result
Try this one -
DECLARE
#str1 VARCHAR(500)
, #str2 VARCHAR(500)
SELECT
#str1 = '10:00am,2:00pm'
, #str2 = '10:00am,12:00pm,2:00pm,4:00pm,6:00pm,8:00pm'
;WITH cte AS
(
SELECT
id = p.value('(./n)[1]', 'INT')
, tm = p.value('(./s)[1]', 'VARCHAR(500)')
FROM (
SELECT field = CAST('<r><s>' + REPLACE(SUBSTRING(t.string + ',', 1, LEN(t.string + ',')), ',', '</s><n>' + CAST(t.id AS VARCHAR(10)) + '</n></r><r><s>') + '</s></r>' AS XML)
FROM (
SELECT string = #str1, id = 1
UNION ALL
SELECT #str2, 2
) t
) d
CROSS APPLY field.nodes('/r') t(p)
WHERE t.p.exist('n') = 1
)
SELECT tm FROM cte WHERE id = 2
EXCEPT
SELECT tm FROM cte WHERE id = 1
Or try this -
;WITH cte2 AS
(
SELECT
t.id
, tm =
SUBSTRING(
',' + t.string + ','
, number + 1
, CHARINDEX(',', ',' + t.string + ',', number + 1) - number - 1)
FROM (
SELECT string = #str1, id = 1
UNION ALL
SELECT #str2, 2
) t
CROSS JOIN [master].dbo.spt_values n
WHERE [type] = 'p'
AND number <= LEN(',' + t.string + ',') - 1
AND SUBSTRING(',' + t.string + ',', number, 1) = ','
)
SELECT tm FROM cte2 WHERE id = 2
EXCEPT
SELECT tm FROM cte2 WHERE id = 1

Find and Remove Repeated Substrings

I've a column in a SQL Server 2008 table where part of the string was accidentally repeated.
Does anyone have a quick and easy way to remove the trailing duplicated substring?
For example,
alpha\bravo\charlie\delta\charlie\delta
should be
alpha\bravo\charlie\delta
If you don't already have a numbers table:
SET NOCOUNT ON;
DECLARE #UpperLimit int = 4000;
;WITH n(rn) AS
(
SELECT ROW_NUMBER() OVER (ORDER BY [object_id])
FROM sys.all_columns
)
SELECT [Number] = rn - 1
INTO dbo.Numbers FROM n
WHERE rn <= #UpperLimit + 1;
CREATE UNIQUE CLUSTERED INDEX n ON dbo.Numbers([Number]);
Now a generic split function, that will turn your delimited string into a set:
CREATE FUNCTION dbo.SplitString
(
#List nvarchar(max),
#Delim char(1)
)
RETURNS TABLE
AS
RETURN ( SELECT
rn,
vn = ROW_NUMBER() OVER (PARTITION BY [Value] ORDER BY rn),
[Value]
FROM
(
SELECT
rn = ROW_NUMBER() OVER (ORDER BY CHARINDEX(#Delim, #List + #Delim)),
[Value] = LTRIM(RTRIM(SUBSTRING(#List, [Number],
CHARINDEX(#Delim, #List + #Delim, [Number]) - [Number])))
FROM dbo.Numbers
WHERE Number <= LEN(#List)
AND SUBSTRING(#Delim + #List, [Number], 1) = #Delim
) AS x
);
GO
And then a function that puts them back together:
CREATE FUNCTION dbo.DedupeString
(
#List nvarchar(max)
)
RETURNS nvarchar(max)
AS
BEGIN
RETURN ( SELECT newval = STUFF((
SELECT N'\' + x.[Value] FROM dbo.SplitString(#List, '\') AS x
WHERE (x.vn = 1)
ORDER BY x.rn
FOR XML PATH(''), TYPE).value(N'./text()[1]', N'nvarchar(max)'), 1, 1, N'')
);
END
GO
Sample usage:
SELECT dbo.DedupeString(N'alpha\bravo\bravo\charlie\delta\bravo\charlie\delta');
Results:
alpha\bravo\charlie\delta
You can also say something like:
UPDATE dbo.MessedUpTable
SET OopsColumn = dbo.DedupeString(OopsColumn);
#MikaelEriksson will probably swoop in with a more efficient way to use XML to eliminate duplicates, but that is what I can offer until then. :-)
create function RemoveDups(#S nvarchar(max)) returns nvarchar(max)
as
begin
declare #R nvarchar(max)
declare #W nvarchar(max)
set #R = ''
while len(#S) > 1
begin
-- Get the first word
set #W = left(#S, charindex('/', #S+'/')-1)
-- Add word to result if not already added
if '/'+#R not like '%/'+#W+'/%'
begin
set #R = #R + #W + '/'
end
-- Remove first word
set #S = stuff(#S, 1, charindex('/', #S+'/'), '')
end
return left(#R, len(#R)- 1)
end
As requested by Aaron Bertrand. I will however make no claim on what is the fastest to execute.
-- Table to replace in
declare #T table
(
ID int identity,
Value nvarchar(max)
)
-- Add some sample data
insert into #T values ('alpha/beta/alpha/gamma/delta/gamma/delta/alpha')
insert into #T values ('delta/beta/alpha/beta/alpha/gamma/delta/gamma/delta/alpha')
-- Update the column
update T
set Value = NewValue
from (
select T1.ID,
Value,
stuff((select '/' + T4.Value
from (
select T3.X.value('.', 'nvarchar(max)') as Value,
row_number() over(order by T3.X) as rn
from T2.X.nodes('/x') as T3(X)
) as T4
group by T4.Value
order by min(T4.rn)
for xml path(''), type).value('.', 'nvarchar(max)'), 1, 1, '') as NewValue
from #T as T1
cross apply (select cast('<x>'+replace(T1.Value, '/', '</x><x>')+'</x>' as xml)) as T2(X)
) as T
select *
from #T

Resources