Loop never ends in SQL Server using While Exists - sql

While Exists (Select * From Col Where Depth Is Null)
Update T
Set T.Depth = P.Depth + 1,
T.Lineage = P.Lineage + LTrim(Str(T.ParentId, 6, 0)) + '/'
From Col T
Join Col P On T.ParentId = P.Id
Where
P.Depth >= 0
And P.Lineage Is Not Null
And T.Depth Is Null

It looks like you're trying to do a recursive query, and the standard way to do that is with a CTE:
;WITH rec AS(
SELECT c.Id, c.Depth, CAST(c.Id AS varchar(MAX) + '/' AS Lineage
FROM Col c
WHERE c.ParentId IS NULL
UNION ALL
SELECT c1.Id, rec.Depth + 1, rec.Lineage + CAST(c1.id as varchar(10)) + '/'
FROM rec
INNER JOIN Col c1 on rec.Id = c1.ParentId
WHERE rec.Depth < 100 --Limit the recursion, set this to what is appropriate for your data
)
--SELECT * FROM rec --Use this first to see if the data is correct, then:
UPDATE T
SET T.Depth = r.Depth, T.Lineage = r.Lineage
FROM Col T
INNER JOIN rec r ON T.Id = r.Id
For more information about CTE's, you can check this technet link.

Related

Resubmit the query without specifying any hints and without using SET FORCEPLAN

In the below query, #employee variable has larger number of characters around 57,000+ characters.
I have not included in the below query, as it will be long text.
When i lessen the values in #employee then the query works perfectly.
When values increase then i get below error.
I am getting this error -
Query processor could not produce a query plan because of the hints
defined in this query. Resubmit the query without specifying any hints
and without using SET FORCEPLAN.
DECLARE #ConfigNo NVARCHAR(100),
#month NVARCHAR(100),
#year NVARCHAR(100),
#company NVARCHAR(100),
#employee NVARCHAR(max)
SET #ConfigNo = '1'
SET #month = '10'
SET #year = '2021'
SET #company = '2'
SET #employee = '613,614,615,616,617,618,619,620,621,622,623,624,625,626,627,628,629,630,631,632,633,634,635,636,637,638,639,640,641,642,643'
EXEC(
'select x.Name,x.Code,x.Id,x.FieldName,x.LabelName,ISNULL(Round(y.Match,2,0),0) Match,x.Amount,x.PrintOrder,1 Flag from (select a.*,(select distinct ISNULL(value,0) from (select T.X.value(''#Value'', ''nvarchar(128)'') as Value, T.X.value(''#Name'', ''nvarchar(128)'') as ColName from dbo.TableTran cross apply TransactionFieldDetails.nodes(''/PayDetails/Column'') as T(X) where EmployeeId = a.Id and MONTH = '
+#month+' and year = '+#year+
') abc where ColName = a.FieldName) Amount from ( select s.FieldName,s.LabelName,isnull(e.FName,'''') + '' '' + isnull(e.LName,'''') as Name,e.Code,e.Id,s.PrintOrder from dbo.TablePrint s cross join dbo.TableDetail e where ComponentType = 1 and e.Id in ('
+#employee+') and s.PayConNo = '+#ConfigNo+' and s.CompanyId = '+#company+
') a ) x left join ( select a.*, (select distinct ISNULL(value,0) from (select T.X.value(''#Value'', ''nvarchar(128)'') as Value, T.X.value(''#Name'', ''nvarchar(128)'') as ColName from dbo.TableTran cross apply TransactionFieldDetails.nodes(''/PayDetails/Column'') as T(X) where EmployeeId = a.Id and MONTH = '
+#month+' and year = '+#year+
') abc where ColName = a.ComputeField) Match from ( select s.ActualField, s.ComputeField,e.FName,e.Id from dbo.PaySlipMatching s cross join dbo.TableDetail e where e.Id in ('
+#employee+') and s.PayConNo = '+#ConfigNo+' and s.CompanyId = '+#company+
') a ) y on x.FieldName = y.ActualField and x.Id = y.Id union all select a.Name,a.Code,a.id,a.FieldName,a.LabelName,0 Match, (select distinct ISNULL(value,0) from (select T.X.value(''#Value'', ''nvarchar(128)'') as Value, T.X.value(''#Name'', ''nvarchar(128)'') as ColName from dbo.TableTran cross apply TransactionFieldDetails.nodes(''/PayDetails/Column'') as T(X) where EmployeeId = a.Id and MONTH = '
+#month+' and year = '+#year+
') abc where ColName = a.FieldName) Amount,a.PrintOrder, 0 Flag from ( select s.FieldName,s.LabelName,isnull(e.FName,'''') + '' '' + isnull(e.LName,'''') as Name,e.Code,e.Id,s.PrintOrder from dbo.TablePrint s cross join dbo.TableDetail e where ComponentType = 2 and e.Id in ('
+#employee+') and s.PayConNo = '+#ConfigNo+' and s.CompanyId = '+#company+
' ) a OPTION (FORCE ORDER)')
Please help me out with any solution or idea.
Formatted Query -
SELECT x.NAME,
x.code,
x.id,
x.fieldname,
x.labelname,
Isnull(Round(y.match, 2, 0), 0) Match,
x.amount,
x.printorder,
1 Flag
FROM (SELECT a.*,
(SELECT DISTINCT Isnull(value, 0)
FROM (SELECT t.x.value('#Value', 'nvarchar(128)') AS Value,
t.x.value('#Name', 'nvarchar(128)') AS ColName
FROM dbo.tabletrans
CROSS apply
transactionfielddetails.nodes('/PayDetails/Column')
AS T(x)
WHERE employeeid = a.id
AND month = 10
AND year = 2021) abc
WHERE colname = a.fieldname) Amount
FROM (SELECT s.fieldname,
s.labelname,
Isnull(e.fname, '') + ' ' + Isnull(e.lname, '') AS NAME,
e.code,
e.id,
s.printorder
FROM dbo.tableprint s
CROSS JOIN dbo.tabledetail e
WHERE componenttype = 1
AND e.id IN ( 25039, 25040, 25041, 25042,
25043, 25044, 25045, 25452 )
AND s.payconno = 1
AND s.companyid = 2) a) x
LEFT JOIN (SELECT a.*,
(SELECT DISTINCT Isnull(value, 0)
FROM (SELECT t.x.value('#Value', 'nvarchar(128)') AS Value,
t.x.value('#Name', 'nvarchar(128)') AS
ColName
FROM dbo.tabletrans
CROSS apply
transactionfielddetails.nodes('/PayDetails/Column')
AS T(x)
WHERE employeeid = a.id
AND month = 10
AND year = 2021) abc
WHERE colname = a.computefield) Match
FROM (SELECT s.actualfield,
s.computefield,
e.fname,
e.id
FROM dbo.payslipmatching s
CROSS JOIN dbo.tabledetail e
WHERE e.id IN ( 25039, 25040, 25041, 25042,
25043, 25044, 25045, 25452 )
AND s.payconno = 1
AND s.companyid = 2) a) y
ON x.fieldname = y.actualfield
AND x.id = y.id
UNION ALL
SELECT a.NAME,
a.code,
a.id,
a.fieldname,
a.labelname,
0 Match,
(SELECT DISTINCT Isnull(value, 0)
FROM (SELECT t.x.value('#Value', 'nvarchar(128)') AS Value,
t.x.value('#Name', 'nvarchar(128)') AS ColName
FROM dbo.tabletrans
CROSS apply
transactionfielddetails.nodes('/PayDetails/Column')
AS T(x)
WHERE employeeid = a.id
AND month = 10
AND year = 2021) abc
WHERE colname = a.fieldname) Amount,
a.printorder,
0 Flag
FROM (SELECT s.fieldname,
s.labelname,
Isnull(e.fname, '') + ' ' + Isnull(e.lname, '') AS NAME,
e.code,
e.id,
s.printorder
FROM dbo.tableprint s
CROSS JOIN dbo.tabledetail e
WHERE componenttype = 2
AND e.id IN ( 25039, 25040, 25041, 25042,
25043, 25044, 25045, 25452 )
AND s.payconno = 1
AND s.companyid = 2) a
OPTION (force ORDER)

SQL split string (all possible combination)

I would like to transform this string:
A1+A2+A3.B1+B2.C1
into
A1.B1.C1
A1.B2.C1
A2.B1.C1
A2.B2.C1
A3.B1.C1
A3.B2.C1
How can I do that? (note that each dimension(= a group separate by .), could have x values, I mean it can be A1+A2.B1.C1 or A1+A2.B1+B2+B3+B4+B5.C1+C2)
Thanks
If you have only 3 columns, then just use STRING_SPLIT: number your groups from first split and then do a join 3 times and select each group on corresponding join.
with a as (
select s2.value as v, dense_rank() over(order by s1.value) as rn
from STRING_SPLIT('A1+A2+A3.B1+B2.C1', '.') as s1
cross apply STRING_SPLIT(s1.value, '+') as s2
)
select
a1.v + '.' + a2.v + '.' + a3.v as val
from a as a1
cross join a as a2
cross join a as a3
where a1.rn = 1
and a2.rn = 2
and a3.rn = 3
| val |
----------
|A1.B1.C1|
|A2.B1.C1|
|A3.B1.C1|
|A1.B2.C1|
|A2.B2.C1|
|A3.B2.C1|
If you have indefinite number of groups, then it's better to use recursive CTE instead of dynamic SQL. What you should do:
Start with all the values from the first group.
On recursion step crossjoin all the values of the next group (i.e. step group number is current group number + 1).
Select the last recursion step where you'll have the result.
Code is below:
with a as (
select s2.value as v, dense_rank() over(order by s1.value) as rn
from STRING_SPLIT('A1+A2+A3.B1+B2+B3+B4.C1+C2.D1+D2+D3', '.') as s1
cross apply STRING_SPLIT(s1.value, '+') as s2
)
, b (val, lvl) as (
/*Recursion base*/
select cast(v as nvarchar(1000)) as val, rn as lvl
from a
where rn = 1
union all
/*Increase concatenation on each iteration*/
select cast(concat(b.val, '.', a.v) as nvarchar(1000)) as val, b.lvl + 1 as lvl
from b
join a
on b.lvl + 1 = a.rn /*Recursion step*/
)
select *
from b
where lvl = (select max(rn) from a) /*You need the last step*/
order by val
I won't add a tabular result since it is quite big. But try it by yourself.
Here is SQL server version and fiddle:
with lst(s) as (select * from STRING_SPLIT('A1+A2.B1+B2+B3+B4+B5.C1+C2','.'))
select t1+'.'+t2+'.'+t3 as res from
(select * from STRING_SPLIT((select s from lst where s like 'A%'), '+')) s1(t1) cross join
(select * from STRING_SPLIT((select s from lst where s like 'B%'), '+')) s2(t2) cross join
(select * from STRING_SPLIT((select s from lst where s like 'C%'), '+')) s3(t3);
Of course you can grow it in a regular fashion if the number of dimensions grows.
Here is a Postgresql solution:
with x(s) as (select string_to_array('A1+A2.B1+B2+B3+B4+B5.C1+C2','.'))
select t1||'.'||t2||'.'||t3 as res from
unnest((select string_to_array(s[1],'+') from x)) t1 cross join
unnest((select string_to_array(s[2],'+') from x)) t2 cross join
unnest((select string_to_array(s[3],'+') from x)) t3;
result:
res |
--------|
A1.B1.C1|
A1.B2.C1|
A1.B3.C1|
A1.B4.C1|
A1.B5.C1|
A2.B1.C1|
A2.B2.C1|
A2.B3.C1|
A2.B4.C1|
A2.B5.C1|
A1.B1.C2|
A1.B2.C2|
A1.B3.C2|
A1.B4.C2|
A1.B5.C2|
A2.B1.C2|
A2.B2.C2|
A2.B3.C2|
A2.B4.C2|
A2.B5.C2|
Here my code with your help. I didn't mention, but I can also have more or less than 3 parts, so I'm using a dynamic SQL for this:
declare #FILTER varchar(max)='B+C+D.A+G.T+Y+R.E'
-- Works also with A.B.C
-- Works also with A+B+C.D.E+F
-- Works also with A+B+C.D+E+F+G+H
declare #NB int
declare #SQL varchar(max)=''
select #NB=count(*) from STRING_SPLIT(#FILTER,'.')
set #SQL='
;with T(A,B) as
(select *, row_number() over (order by (select NULL))
from STRING_SPLIT(''' + #FILTER + ''',''.'')
)
select '
;with T(V,N) as (
select *, row_number() over (order by (select NULL))
from STRING_SPLIT(#FILTER,'.')
)
select #SQL=#SQL + 'T' + cast(N as varchar(max)) + ' + ''.'' + ' from T
set #SQL=left(#SQL,len(#SQL)-1) + ' as res from'
;with T(V,N) as (
select *, row_number() over (order by (select NULL))
from STRING_SPLIT(#FILTER,'.')
)
select #SQL=#SQL + '
(select * from STRING_SPLIT((select A from T where B=' + cast(N as varchar(max)) + '), ''+'')) s' + cast(N as varchar(max)) + '(t' + cast(N as varchar(max)) + ') cross join'
from T
set #SQL=left(#SQL,len(#SQL)-len('cross join'))
exec(#SQL)

How to create path with sql query

What is the best solution :
I have a table in sqlserver with these contents .
PARENT CHILD Level
A B 0
B C 1
C D 2
D E 3
I need a query to create this result :
A/B/C/D/E
You can use a recursive CTE for this:
with cte as (
select t.parent as p, t.parent as c, 0 as lev
from table t
where not exists (select 1 from t t2 where t2.child = t.parent)
union all
select cte.p, t.child, lev + 1
from cte join
table t
on cte.c = t.parent
)
select stuff((select '/' + cte2.c
from cte cte2
where cte2.p = cte.p
order by cte2.lev
for xml path ('')
), 1, 1, '') as path
from cte
group by cte.p;
Here is a SQL Fiddle.
Use Coalesce to combine rows into single column separated by '/' delimiter
DECLARE #path VARCHAR(8000) = (SELECT parent FROM test WHERE LEVEL = 0)
SELECT #path = COALESCE(rtrim(#path) + '/', '') + child FROM test
SELECT #path

recursive query with peer relations

Let's say there is a table of relationships
(entity_id, relationship, related_id)
1, A, 2
1, A, 3
3, B, 5
1, C, null
12, C, 1
100, C, null
I need a query that will pull all related rows.
For example, if i queried for entity_id = 1, the following rows should be pulled
1, A, 2
1, A, 3
3, B, 5
1, C, null
12, C, 1
Actually, if i queried for entity_id = 1, 2, 3, 5, or 12, the resultset should be the same.
This is different than the standard manager-employee paradigm as there is no hierarchy. The relationships can go in any direction.
EDIT
None of the answers posted thus far worked.
I was able to come up with a solution that works.
I'll give the solution credit to the one who can clean this monstrosity into something more elegant.
with tab as (
-- union for reversals
select id, entity_id, r.related_id, 1 level
, cast('/' + cast(entity_id as varchar(1000)) + '/' as varchar(1000)) path
from _entity_relation r
where not exists(select null from _entity_relation r2 where r2.related_id=r.entity_id)
or r.related_id is null
union
select id, related_id, r.entity_id, 1 level
, cast('/' + cast(related_id as varchar(1000)) + '/' as varchar(1000)) path
from _entity_relation r
where not exists(select null from _entity_relation r2 where r2.related_id=r.entity_id)
or r.related_id is null
-- create recursive path
union all
select r.id, r.entity_id, r.related_id, tab.level+1
, cast(tab.path + '/' + cast(r.entity_id as varchar(100)) + '/' + '/' + cast(r.related_id as varchar(1000)) + '/' as varchar(1000)) path
from _entity_relation r
join tab
on tab.related_id = r.entity_id
)
select x.id
, x.entity_id
,pr.description as relation_description
,pt.first_name + coalesce(' ' + pt.middle_name,'') + ' ' + pt.last_name as relation_name
,CONVERT(CHAR(10), pt.birth_date, 101) as relation_birth_date
from (
select entity_id, MAX(id) as id from (
select distinct tab.id, entity_id
from tab
join(
select path
from tab
where entity_id=#in_entity_id
) p on p.path like tab.path + '%' or tab.path like p.path + '%'
union
select distinct tab.id, related_id
from tab
join(
select path
from tab
where entity_id=#in_entity_id
) p on p.path like tab.path + '%' or tab.path like p.path + '%'
union
select distinct tab.id, entity_id
from tab
join(
select path
from tab
where related_id=#in_entity_id
) p on p.path like tab.path + '%' or tab.path like p.path + '%'
union
select distinct tab.id, related_id
from tab
join(
select path
from tab
where related_id=#in_entity_id
) p on p.path like tab.path + '%' or tab.path like p.path + '%'
) y
group by entity_id
) x
join _entity_relation pr on pr.id = x.id
join _entity pt on pt.id = x.entity_id
where x.entity_id <> #in_entity_id;
Please be careful with you data as to accomplish your task you must avoid circular references. The following query can be optimized but for sure it'll work
;with tab as (
select entity_id, relationship, related_id, 1 level, cast('/' + cast(entity_id as varchar(1000)) as varchar(1000)) path
from #r r
where not exists(select null from #r r2 where r2.related_id=r.entity_id)
or r.related_id is null
union all
select r.entity_id, r.relationship, r.related_id, tab.level+1, cast(tab.path + '/' + cast(r.entity_id as varchar(100)) as varchar(1000)) path
from #r r
join tab
on tab.related_id = r.entity_id
)
select distinct tab.*
from tab
join(
select path
from tab
where entity_id=1) p
on p.path like tab.path + '%' or tab.path like p.path + '%'
Solution using two CTEs
I first created a table with relationships that go both ways and then created a recursive CTE that uses this both ways results to build whole hierarchies with ancestor paths...
with both as
(
select *, 0 as rev
from t
where related_id is not null
union
select *, 1
from t
),
recurs as
(
select *, cast('/' as varchar(100)) as anc
from both
where entity_id is null
union all
select b.*, cast(re.anc + cast(b.entity_id as varchar) + '/' as varchar(100))
from both b
join recurs re
on (re.related_id = b.entity_id)
where charindex('/'+cast(isnull(b.entity_id,'') as varchar)+'/', re.anc) = 0
)
select *
/*
THIS ONE SHOULD BE USED TO RETURN TO ORIGINAL
case when is_reverse = 1 then related_id else entity_id end as entity_id,
relationship,
case when is_reverse = 0 then related_id else entity_id end as related_id
*/
from recurs
where related_id = xXx or
charindex('/'+cast(xXx as varchar)+'/', anc) != 0
Replace xXx with actual value.
This query assumes that root element is the one with entity_id = null, so it builds the whole recursion from there. If that's not the case you'll have to change it accordingly.
I've added loop checks either loops are 1,2,3,4,5,1 or 1,2,3,4,5,3... So total or partial loops. Both will work.

STORED PROCEDURE working in my local test machine cannot be created in production environment

I have an SQL CREATE PROCEDURE statement that runs perfectly in my local SQL Server, but cannot be recreated in production environment. The error message I get in production is Msg 102, Level 15, State 1, Incorrect syntax near '='.
It is a pretty big query and I don't want to annoy StackOverflow users, but I simply can't find a solution. If only you could point me out what settings I could check in the production server in order to enable running the code... I must be using some kind of syntax or something that is conflicting with some setting in production. This PROCEDURE was already registered in production before, but when I ran a DROP - CREATE PROCEDURE today, the server was able to drop the procedure, but not to recreate it.
I will paste the code below. Thank you!
===============
USE [Enorway]
GO
/****** Object: StoredProcedure [dbo].[Spel_CM_ChartsUsersTotals] Script Date: 03/17/2010 11:59:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[Spel_CM_ChartsUsersTotals]
#IdGroup int,
#IdAssessment int,
#UserId int
AS
SET NOCOUNT ON
DECLARE #RequiredColor varchar(6)
SET #RequiredColor = '3333cc'
DECLARE #ManagersColor varchar(6)
SET #ManagersColor = '993300'
DECLARE #GroupColor varchar(6)
SET #GroupColor = 'ff0000'
DECLARE #SelfColor varchar(6)
SET #SelfColor = '336600'
DECLARE #TeamColor varchar(6)
SET #TeamColor = '993399'
DECLARE #intMyCounter tinyint
DECLARE #intManagersPosition tinyint
DECLARE #intGroupPosition tinyint
DECLARE #intSelfPosition tinyint
DECLARE #intTeamPosition tinyint
SET #intMyCounter = 1
-- Table that will hold the subtotals...
DECLARE #tblTotalsSource table
(
IdCompetency int,
CompetencyName nvarchar(200),
FunctionRequiredLevel float,
ManagersAverageAssessment float,
SelfAssessment float,
GroupAverageAssessment float,
TeamAverageAssessment float
)
INSERT INTO #tblTotalsSource
(
IdCompetency,
CompetencyName,
FunctionRequiredLevel,
ManagersAverageAssessment,
SelfAssessment,
GroupAverageAssessment,
TeamAverageAssessment
)
SELECT
e.[IdCompetency],
dbo.replaceAccentChar(e.[Name]) AS CompetencyName,
(i.[LevelNumber]) AS FunctionRequiredLevel,
(
SELECT
ROUND(avg(CAST(ac.[LevelNumber] AS float)),0)
FROM
Spel_CM_AssessmentsData aa
INNER JOIN Spel_CM_CompetenciesLevels ab ON aa.[IdCompetencyLevel] = ab.[IdCompetencyLevel]
INNER JOIN Spel_CM_Levels ac ON ab.[IdLevel] = ac.[IdLevel]
INNER JOIN Spel_CM_AssessmentsEvents ad ON aa.[IdAssessmentEvent] = ad.[IdAssessmentEvent]
WHERE
aa.[EvaluatedUserId] = #UserId AND
aa.[AssessmentType] = 't' AND
aa.[IdGroup] = #IdGroup AND
ab.[IdCompetency] = e.[IdCompetency] AND
ad.[IdAssessment] = #IdAssessment
) AS ManagersAverageAssessment,
(
SELECT
bc.[LevelNumber]
FROM
Spel_CM_AssessmentsData ba
INNER JOIN Spel_CM_CompetenciesLevels bb ON ba.[IdCompetencyLevel] = bb.[IdCompetencyLevel]
INNER JOIN Spel_CM_Levels bc ON bb.[IdLevel] = bc.[IdLevel]
INNER JOIN Spel_CM_AssessmentsEvents bd ON ba.[IdAssessmentEvent] = bd.[IdAssessmentEvent]
WHERE
ba.[EvaluatedUserId] = #UserId AND
ba.[AssessmentType] = 's' AND
ba.[IdGroup] = #IdGroup AND
bb.[IdCompetency] = e.[IdCompetency] AND
bd.[IdAssessment] = #IdAssessment
) AS SelfAssessment,
(
SELECT
ROUND(avg(CAST(cc.[LevelNumber] AS float)),0)
FROM
Spel_CM_AssessmentsData ca
INNER JOIN Spel_CM_CompetenciesLevels cb ON ca.[IdCompetencyLevel] = cb.[IdCompetencyLevel]
INNER JOIN Spel_CM_Levels cc ON cb.[IdLevel] = cc.[IdLevel]
INNER JOIN Spel_CM_AssessmentsEvents cd ON ca.[IdAssessmentEvent] = cd.[IdAssessmentEvent]
WHERE
ca.[EvaluatedUserId] = #UserId AND
ca.[AssessmentType] = 'g' AND
ca.[IdGroup] = #IdGroup AND
cb.[IdCompetency] = e.[IdCompetency] AND
cd.[IdAssessment] = #IdAssessment
) AS GroupAverageAssessment,
(
SELECT
ROUND(avg(CAST(dc.[LevelNumber] AS float)),0)
FROM
Spel_CM_AssessmentsData da
INNER JOIN Spel_CM_CompetenciesLevels db ON da.[IdCompetencyLevel] = db.[IdCompetencyLevel]
INNER JOIN Spel_CM_Levels dc ON db.[IdLevel] = dc.[IdLevel]
INNER JOIN Spel_CM_AssessmentsEvents dd ON da.[IdAssessmentEvent] = dd.[IdAssessmentEvent]
WHERE
da.[EvaluatedUserId] = #UserId AND
da.[AssessmentType] = 'm' AND
da.[IdGroup] = #IdGroup AND
db.[IdCompetency] = e.[IdCompetency] AND
dd.[IdAssessment] = #IdAssessment
) AS TeamAverageAssessment
FROM
Spel_CM_AssessmentsData a
INNER JOIN Spel_CM_AssessmentsEvents c ON a.[IdAssessmentEvent] = c.[IdAssessmentEvent]
INNER JOIN Spel_CM_CompetenciesLevels d ON a.[IdCompetencyLevel] = d.[IdCompetencyLevel]
INNER JOIN Spel_CM_Competencies e ON d.[IdCompetency] = e.[IdCompetency]
INNER JOIN Spel_CM_Levels f ON d.[IdLevel] = f.[IdLevel]
-- This will link with user's assigned functions
INNER JOIN Spel_CM_FunctionsCompetenciesLevels g ON a.[IdFunction] = g.[IdFunction]
INNER JOIN Spel_CM_CompetenciesLevels h ON g.[IdCompetencyLevel] = h.[IdCompetencyLevel] AND e.[IdCompetency] = h.[IdCompetency]
INNER JOIN Spel_CM_Levels i ON h.[IdLevel] = i.[IdLevel]
WHERE
(NOT c.[EndDate] IS NULL) AND
a.[EvaluatedUserId] = #UserId AND
c.[IdAssessment] = #IdAssessment AND
a.[IdGroup] = #IdGroup
GROUP BY
e.[IdCompetency],
e.[Name],
i.[LevelNumber]
ORDER BY
e.[Name] ASC
-- This will define the position of each element (managers, group, self and team)
SELECT #intManagersPosition = #intMyCounter FROM #tblTotalsSource WHERE NOT ManagersAverageAssessment IS NULL
IF IsNumeric(#intManagersPosition) = 1 BEGIN SELECT #intMyCounter += 1 END
SELECT #intGroupPosition = #intMyCounter FROM #tblTotalsSource WHERE NOT GroupAverageAssessment IS NULL
IF IsNumeric(#intGroupPosition) = 1 BEGIN SELECT #intMyCounter += 1 END
SELECT #intSelfPosition = #intMyCounter FROM #tblTotalsSource WHERE NOT SelfAssessment IS NULL
IF IsNumeric(#intSelfPosition) = 1 BEGIN SELECT #intMyCounter += 1 END
SELECT #intTeamPosition = #intMyCounter FROM #tblTotalsSource WHERE NOT TeamAverageAssessment IS NULL
-- This will render the final table for the end user. The tabe will flatten some of the numbers to allow them to be prepared for Google Graphics.
SELECT
SUBSTRING(
(
SELECT
( '|' + REPLACE(ma.[CompetencyName],' ','+'))
FROM
#tblTotalsSource ma
ORDER BY
ma.[CompetencyName] DESC
FOR XML PATH('')
), 2, 1000) AS 'CompetenciesNames',
SUBSTRING(
(
SELECT
( ',' + REPLACE(ra.[FunctionRequiredLevel]*10,' ','+'))
FROM
#tblTotalsSource ra
FOR XML PATH('')
), 2, 1000) AS 'FunctionRequiredLevel',
SUBSTRING(
(
SELECT
( ',' + CAST(na.[ManagersAverageAssessment]*10 AS nvarchar(10)))
FROM
#tblTotalsSource na
FOR XML PATH('')
), 2, 1000) AS 'ManagersAverageAssessment',
SUBSTRING(
(
SELECT
( ',' + CAST(oa.[GroupAverageAssessment]*10 AS nvarchar(10)))
FROM
#tblTotalsSource oa
FOR XML PATH('')
), 2, 1000) AS 'GroupAverageAssessment',
SUBSTRING(
(
SELECT
( ',' + CAST(pa.[SelfAssessment]*10 AS nvarchar(10)))
FROM
#tblTotalsSource pa
FOR XML PATH('')
), 2, 1000) AS 'SelfAssessment',
SUBSTRING(
(
SELECT
( ',' + CAST(qa.[TeamAverageAssessment]*10 AS nvarchar(10)))
FROM
#tblTotalsSource qa
FOR XML PATH('')
), 2, 1000) AS 'TeamAverageAssessment',
SUBSTRING(
(
SELECT
( '|t++' + CAST([FunctionRequiredLevel] AS varchar(10)) + ',' + #RequiredColor + ',0,' + CAST(ROW_NUMBER() OVER(ORDER BY CompetencyName) - 1 AS varchar(2)) + ',9')
FROM
#tblTotalsSource
FOR XML PATH('')
), 2, 1000) AS 'FunctionRequiredAverageLabel',
SUBSTRING(
(
SELECT
( '|t++' + CAST([ManagersAverageAssessment] AS varchar(10)) + ',' + #ManagersColor + ',' + CAST(#intManagersPosition AS varchar(2)) + ',' + CAST(ROW_NUMBER() OVER(ORDER BY CompetencyName) - 1 AS varchar(2)) + ',9')
FROM
#tblTotalsSource
FOR XML PATH('')
), 2, 1000) AS 'ManagersLabel',
SUBSTRING(
(
SELECT
( '|t++' + CAST([GroupAverageAssessment] AS varchar(10)) + ',' + #GroupColor + ',' + CAST(#intGroupPosition AS varchar(2)) + ',' + CAST(ROW_NUMBER() OVER(ORDER BY CompetencyName) - 1 AS varchar(2)) + ',9')
FROM
#tblTotalsSource
FOR XML PATH('')
), 2, 1000) AS 'GroupLabel',
SUBSTRING(
(
SELECT
( '|t++' + CAST([SelfAssessment] AS varchar(10)) + ',' + #SelfColor + ',' + CAST(#intSelfPosition AS varchar(2)) + ',' + CAST(ROW_NUMBER() OVER(ORDER BY CompetencyName) - 1 AS varchar(2)) + ',9')
FROM
#tblTotalsSource
FOR XML PATH('')
), 2, 1000) AS 'SelfLabel',
SUBSTRING(
(
SELECT
( '|t++' + CAST([TeamAverageAssessment] AS varchar(10)) + ',' + #TeamColor + ',' + CAST(#intTeamPosition AS varchar(2)) + ',' + CAST(ROW_NUMBER() OVER(ORDER BY CompetencyName) - 1 AS varchar(2)) + ',10')
FROM
#tblTotalsSource
FOR XML PATH('')
), 2, 1000) AS 'TeamLabel',
(Count(src.[IdCompetency]) * 30) + 100 AS 'ControlHeight'
FROM
#tblTotalsSource src
SET NOCOUNT OFF
GO
Search your stored procedure for instances of this string: += (you have a few of them). This combined operator is not supported by T-SQL,
So instead of this:
SELECT #intMyCounter += 1
you will need to do this instead:
SELECT #intMyCounter = #intMyCounter + 1
when you run your create procedure script in sql server management studio and you get an error, double click on the error message and it usually takes you to the line where the error occurs. Sometimes this is just the first line of a long SELECT query, but in this case it is fairly obvious, because it is a one line IF
you can not use += in the line:
IF IsNumeric(#intManagersPosition) = 1 BEGIN SELECT #intMyCounter += 1 END
should be:
IF IsNumeric(#intManagersPosition) = 1 BEGIN SELECT #intMyCounter = #intMyCounter+1 END
you do this three times, fix then and you are good to go.
don't you miss BEGIN and END in the beginnning and eding of procedure, respectively?
(create procedure blablabla as begin .... end)
If SQL isn't giving you a line number, try commenting out different statements and re-running the command