Issue with full outer join in SQL Server - sql

When I use below 2 queries separately I get output successfully
Query #1
DECLARE #ID VARCHAR(1000)
SET #ID = ''
SELECT #ID = #ID + CAST(int_ID AS VARCHAR(1000))
FROM MATRIX_RELATIONSHIP
SELECT COUNT(int_ID) [Count], YEAR(dt_5841_OF) [date]
FROM TRANS_IDENTIFICATIONS
WHERE smallint_209_ME = 4
AND CHARINDEX(CONVERT(VARCHAR, int_ID), ('''' + Replace((#ID),',',''',''') + '''')) > 0
GROUP BY YEAR(dt_5841_OF);
Output:
Count | year
02 2016
Query #2
SELECT
COUNT(*) [Count1], YEAR(dt_modifiedOn) [date]
FROM
MATRIX_RELATIONSHIP
GROUP BY
YEAR(dt_modifiedOn);
Output:
Count | year
02 2016
But when I use both queries to form a full outer join something like below:
SELECT
tab1.Count, tab2.Count1, tab1.date
FROM
(DECLARE #ID VARCHAR(1000)
SET #ID = ''
SELECT #ID = #ID+CAST(int_ID AS VARCHAR(1000))
FROM MATRIX_RELATIONSHIP
SELECT COUNT(int_ID) [Count], YEAR(dt_5841_OF) [date]
FROM TRANS_IDENTIFICATIONS
WHERE smallint_209_ME = 4
AND CHARINDEX(convert(varchar,int_ID), ('''' + Replace((#ID),',',''',''') + '''')) > 0
GROUP BY YEAR(dt_5841_OF)) tab1
FULL OUTER JOIN
(SELECT COUNT(*) [Count1], YEAR(dt_modifiedOn) [date]
FROM MATRIX_RELATIONSHIP
GROUP BY YEAR(dt_modifiedOn)) tab2 ON tab1.date = tab2.date;
I get these errors:
Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'DECLARE'.
Msg 102, Level 15, State 1, Line 4
Incorrect syntax near ')'.
Msg 102, Level 15, State 1, Line 7
Incorrect syntax near 'tab2'.
Expected result
Count | Count1 | year
02 02 2016
EDIT
I have tried placing declare and set outside the query too but still there the issue persists
DECLARE #ID VARCHAR(1000) SET #ID=''
SELECT tab1.Count,tab2.Count1,tab1.date from
( SELECT #ID= #ID+CAST(int_ID AS VARCHAR(1000))
from MATRIX_RELATIONSHIP SELECT COUNT(int_ID)[Count],YEAR(dt_5841_OF)[date] FROM TRANS_IDENTIFICATIONS WHERE smallint_209_ME=4 and CHARINDEX(convert(varchar,int_ID), ('''' + Replace((#ID),',',''',''') + '''')) >
0 GROUP BY YEAR(dt_5841_OF)) tab1
FULL OUTER JOIN
(SELECT COUNT(*)[Count1],YEAR(dt_modifiedOn)[date]
FROM MATRIX_RELATIONSHIP GROUP BY YEAR(dt_modifiedOn)) tab2
ON tab1.date=tab2.date;
Which leads to another set of errors:
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '='.
Msg 102, Level 15, State 1, Line 5
Incorrect syntax near ')'.
Msg 102, Level 15, State 1, Line 8
Incorrect syntax near 'tab2'.

DECLARE #ID VARCHAR(1000)
SET #ID='';
SELECT #ID = #ID + CAST(int_ID AS VARCHAR(1000)) from MATRIX_RELATIONSHIP;
SELECT MAX(Count) AS Count, MAX(Count1) AS Count1, date
FROM
(
SELECT COUNT(int_ID)[Count], null AS [Count1], YEAR(dt_5841_OF)[date]
FROM TRANS_IDENTIFICATIONS
WHERE smallint_209_ME = 4
and CHARINDEX(convert(varchar,int_ID), ('''' + Replace((#ID),',',''',''') + '''')) >
0 GROUP BY YEAR(dt_5841_OF)
UNION ALL
SELECT NULL AS [Count], COUNT(*)[Count1],YEAR(dt_modifiedOn)[date]
FROM MATRIX_RELATIONSHIP
GROUP BY YEAR(dt_modifiedOn)
)AS temp
GROUP BY [date]

this is not a valid from
it is two select statements
from
( DECLARE #ID VARCHAR(1000)
SET #ID='' SELECT #ID= #ID+CAST(int_ID AS VARCHAR(1000))
from MATRIX_RELATIONSHIP
SELECT COUNT(int_ID)[Count],YEAR(dt_5841_OF)[date]
FROM TRANS_IDENTIFICATIONS
WHERE smallint_209_ME=4
and CHARINDEX(convert(varchar,int_ID), ('''' + Replace((#ID),',',''',''') + '''')) > 0
GROUP BY YEAR(dt_5841_OF)
)

Your DECLARE and SET has to be outside of the SELECT. But what is its purpose?

remove the DECLARE #ID VARCHAR(1000);
SET #ID='' from the select statement.
Also declare the variable at the top of your statement
and rather writing two separate select statement use inner join on int_id and then do the outer join it will work

DECLARE #ID VARCHAR(1000)
SET #ID = ''
select * from
(
SELECT #ID+ CAST(MATRIX_RELATIONSHIP.int_ID AS varchar(1000)) AS count1, COUNT(TRANS_IDENTIFICATIONS.int_ID) AS count2, YEAR(TRANS_IDENTIFICATIONS.dt_5841_OF) AS date1
FROM MATRIX_RELATIONSHIP INNER JOIN
TRANS_IDENTIFICATIONS ON MATRIX_RELATIONSHIP.int_ID = TRANS_IDENTIFICATIONS.int_ID
WHERE (TRANS_IDENTIFICATIONS.smallint_209_ME = 4) AND (CHARINDEX(CONVERT(varchar, TRANS_IDENTIFICATIONS.int_ID), '''' + REPLACE(#ID, ',', ''',''') + '''') > 0)
GROUP BY YEAR(TRANS_IDENTIFICATIONS.dt_5841_OF),MATRIX_RELATIONSHIP.int_ID
union
(
SELECT '' as count1, COUNT(*) [Count2], YEAR(dt_modifiedOn) [date1]
FROM MATRIX_RELATIONSHIP
GROUP BY YEAR(dt_modifiedOn)
)
) as tbl
I hope this works for you... Do let me know

Related

PIVOT in SQL Server does not support Select statement

I get these errors:
Msg 156, Level 15, State 1, Line 22
Incorrect syntax near the keyword 'select'.
Msg 102, Level 15, State 1, Line 22
Incorrect syntax near ')'
when running this code:
Select *
from
(select
DWF_Week_No
,DWF_Fuel_Name
,DWF_T_Sale
from
QF_FDashboard_Week_Fuel
where
DWF_Month_Name = 'October'
and DWF_Location_Name = 'Fitzroy') t
pivot
(sum(DWF_T_Sale)
for DWF_Fuel_Name in (select distinct DWF_Fuel_Name from QF_FDashboard_Week_Fuel)
) as pivot_table;
It is not possible to put a SELECT inside the IN in the PIVOT. You can find a workaround here. In your case it would be something like this:
DECLARE #col nvarchar(max) = (stuff( ( select distinct ',[' + Ltrim(rtrim(DWF_Fuel_Name)) +']' from QF_FDashboard_Week_Fuel FOR XML PATH('')),1,1,''))
EXEC('Select *
from
(select
DWF_Week_No
,DWF_Fuel_Name
,DWF_T_Sale
from
QF_FDashboard_Week_Fuel
where
DWF_Month_Name = ''October''
and DWF_Location_Name = ''Fitzroy'') t
pivot
(sum(DWF_T_Sale)
for DWF_Fuel_Name in ('+#col+')
) as pivot_table;
')

Syntax error in SQL job in Azure SQL database

I am inserting a job step in Azure Elastic job agent. This is my code:
EXEC jobs.sp_add_jobstep #job_name='Sample T-SQL',
#command=N' declare #columns varchar(max)
select #columns = stuff(( select '],[' + [$Name]
from dbo.groups
order by '],[' + convert(varchar(max), [$_ClosingBalance]) desc
for xml path('')), 1, 2, '' + ']'
INSERT INTO dbo.Trial1
( [Bank Accounts],[Bank OD A/c],[Branch / Divisions],[Capital Account],[Cash-in-Hand],[Current Assets],[Current Liabilities],[Deposits (Asset)]
,[Direct Expenses],[Direct Incomes],[Duties & Taxes],[Fixed Assets],[Duties & Taxes1],[Duties & Taxes2],[Indirect Expenses],[Indirect Incomes],[Investments]
,[Loans & Advances (Asset)],[Loans (Liability)],[Misc# Expenses (ASSET)],[Provisions],[Purchase Accounts],[Reserves & Surplus],[Sales Accounts],[Secured Loans]
,[Stock-in-Hand],[Stock Transfer Outward],[Sundry Creditors],[Sundry Debtors],[Suspense A/c],[Duties & Taxes3]
,[Unsecured Loans]
)
Select * from (
Select [$_ClosingBalance], RowN = Row_Number() over (order by #columns) from dbo.Groups
) a
pivot (max([$_ClosingBalance]) for RowN in ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31],[32])) p
INSERT INTO dbo.Date ([Date]) VALUES (GETDATE())
INSERT INTO dbo.Final
SELECT *
FROM dbo.Trial1
INNER JOIN dbo.Date
ON dbo.Trial1.IdCol = dbo.Date.IDCol1'',
#credential_name='JobRun',
#target_group_name='DatabaseGroup5'
I am receiving the following error :
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near ']'.
Msg 137, Level 15, State 2, Line 15
Must declare the scalar variable "#columns".
Msg 102, Level 15, State 1, Line 24
Incorrect syntax near ''
My code is ending where it should not. Please help.
after that you assigned #command ,you can write : print #command
then you can look printed script ,copy it and paste in query window.then probebly you will understand your mistake.

Error Incorrect syntax near the keyword 'SELECT'

I need help.
I write this query
SELECT SUM(fi.etiliquido) FROM fi WHERE fi.fno IN (
SELECT * from divideString(
SELECT TOP 1 REPLACE(CAST( u.nrdoc AS nvarchar),'/',',') FROM u_ups1 as u WHERE 1057 IN (
SELECT * FROM divideString(REPLACE(CAST(u.nrdoc AS nvarchar),'/',','))
)
)
)
but sql server return this error
Msg 156, Level 15, State 1, Line 4 Incorrect syntax near the keyword
'SELECT'. Msg 102, Level 15, State 1, Line 7 Incorrect syntax near
')'.
and I don't know why.
Can you help me?
UPDATE
divideString is a function get a string and returns the numbers in that string
CREATE FUNCTION divideString (#InStr VARCHAR(MAX))
RETURNS #TempTab TABLE
(id int not null)
AS
BEGIN
SET #InStr = REPLACE(#InStr + ',', ',,', ',')
DECLARE #SP INT
DECLARE #VALUE VARCHAR(1000)
WHILE PATINDEX('%,%', #INSTR ) <> 0
BEGIN
SELECT #SP = PATINDEX('%,%',#INSTR)
SELECT #VALUE = LEFT(#INSTR , #SP - 1)
SELECT #INSTR = STUFF(#INSTR, 1, #SP, '')
INSERT INTO #TempTab(id) VALUES (#VALUE)
END
RETURN
END
You need parentheses around subqueries (except for in subqueries), so:
SELECT SUM(fi.etiliquido)
FROM fi
WHERE fi.fno IN (SELECT d.val
FROM divideString( (SELECT TOP 1 REPLACE(CAST( u.nrdoc AS nvarchar(max)), '/', ',')
FROM u_ups1 as u
WHERE 1057 IN (SELECT d.val
FROM divideString(REPLACE(CAST(u.nrdoc AS nvarchar(max)), '/', ',') d(val)
)
)
) d(val)
);
Also, using TOP with no ORDER BY is usually suspicious.
Storing multiple values in a single column is not recommended. However, I don't think you need a table-valued functions for this. LIKE should work:
SELECT SUM(fi.etiliquido)
FROM fi
WHERE EXISTS (SELECT 1
FROM (SELECT TOP 1 u.nrdoc
FROM u_ups1 u
WHERE '/' + u.nrdoc + '/' LIKE '%/1057/%'
) u
WHERE '/' + u.nrdoc + '/' LIKE '%/' + fi.fno + '/%'
);
And what you might want:
And, the logic that you want might be as simple as this:
SELECT SUM(fi.etiliquido)
FROM fi
WHERE EXISTS (SELECT 1
FROM u_ups1 u
WHERE '/' + u.nrdoc + '/' LIKE '%/1057/%' AND
'/' + u.nrdoc + '/' LIKE '%/' + fi.fno + '/%'
);

SQL Server 2008 - MERGE INTO as a loop: syntax error

I am attempting to run an SQL query, which includes a MERGE INTO statement, that loops through each month.
I am getting a couple of syntax errors:
Msg 156, Level 15, State 1, Line 3 Incorrect syntax near the keyword 'INTO'.
Msg 156, Level 15, State 1, Line 10 Incorrect syntax near the keyword 'AS'.
Msg 102, Level 15, State 1, Line 35 Incorrect syntax near ','.
It is printing the month/year correctly so I don't think the problem is in the loop, but the merge statement. I looked around but it looks right to me but I am sure I am missing something. I could have sworn I used this code before and it worked.
Here is the code:
Declare #StartDate As Datetime set #StartDate = '5/1/2015'; --Update to first month that needs to be added
Declare #StopDate As Datetime set #StopDate = '12/1/2015'; --Update to last month that needs to be added
Print 'Start Date ' + Cast(#StartDate as varchar(30));
Print 'Stop Date ' + Cast(#StopDate as varchar(30));
Print 'Total Months ' + Cast(Datediff(Month, #StartDate, #StopDate) + 1 as varchar(30));
Print ' ';
Declare #Date As Datetime set #Date = #StartDate;
Declare #SQL_Cmd As Varchar(Max);
Declare #SQL_Contract_Status As Varchar(Max) set #SQL_Contract_Status =
'
MERGE
INTO ANNUSER1.RPS_Contract_Person_PT AS TGT
USING ( Select
P.Datamart_Timestamp
,P.Contract_ID
,P.DOB
,Ltrim(Rtrim(
CASE
WHEN P.Datamart_Timestamp
< CONVERT(DATETIME, ''2007-06-01 00:00:00'', 102)
AND Len(P.Name_Last) > 25
THEN Substring(P.Name_Last,26,Len(P.Name_Last)-25)
ELSE P.Name_First
END)) As Name_First
,Ltrim(Rtrim(
CASE
WHEN P.Datamart_Timestamp
< CONVERT(DATETIME, ''2007-06-01 00:00:00'', 102)
AND Len(P.Name_Last) > 25
THEN LTrim(Left(P.Name_Last,25))
ELSE P.Name_Last
END)) As Name_Last
,P.Sex
,P.TIN
,P.TIN_Type
,D.Group_Plan_ID
From AT_RPS_2015_05_Contract_Person AS P
INNER JOIN AT_RPS_2015_05_Contract_Data AS D
ON P.Contract_ID = D.Contract_ID
WHERE (P.[Role] IN (''PT''))
) AS SRC
ON ( TGT.Contract_ID = SRC.Contract_ID )
AND ( TGT.DOB = Cast(SRC.DOB as Date)
OR ( TGT.DOB IS NULL
AND SRC.DOB IS NULL ) )
AND ( TGT.Name_First = SRC.Name_First
OR ( TGT.Name_First IS NULL
AND SRC.Name_First IS NULL ) )
AND ( TGT.Name_Last = SRC.Name_Last
OR ( TGT.Name_Last IS NULL
AND SRC.Name_Last IS NULL ) )
AND ( TGT.Sex = SRC.Sex
OR ( TGT.Sex IS NULL
AND SRC.Sex IS NULL ) )
AND ( TGT.TIN = SRC.TIN
OR ( TGT.TIN IS NULL
AND SRC.TIN IS NULL ) )
AND ( TGT.TIN_Type = SRC.TIN_Type
OR ( TGT.TIN_Type IS NULL
AND SRC.TIN_Type IS NULL ) )
WHEN NOT MATCHED
THEN
INSERT
(
Contract_ID
,Sequence_Number
,DOB
,Name_First
,Name_Last
,Sex
,TIN
,TIN_Type
,Datamart_Timestamp
,Group_Plan_ID
)
VALUES
(
SRC.Contract_ID
,Coalesce(
(SELECT Max(Sequence_Number)
FROM ANNUSER1.RPS_Contract_Person_PT AS TGT
WHERE TGT.Contract_ID = SRC.Contract_ID)
,0) + 1
,Cast(SRC.DOB as Datetime)
,SRC.Name_First
,SRC.Name_Last
,SRC.Sex
,SRC.TIN
,SRC.TIN_Type
,Cast(SRC.Datamart_Timestamp As Datetime)
,SRC.Group_Plan_ID
); ';
While #Date <= #StopDate
Begin
Set #SQL_Cmd = Replace(Replace(#SQL_Contract_Status, 'YYYY', Year(#Date)), 'MM', Right('0' + Cast(Month(#Date) As Varchar(2)), 2));
Exec (#SQL_Cmd);
Print Cast(Year(#Date) as varchar(30)) + '_' + Right('0' + Cast(Month(#Date) as varchar(30)),2) + ' ' + Cast(##RowCount as varchar(30));
Set #Date = Dateadd(Month, 1, #date);
End;
GO

Passing column value in stored procedure in sql

Create Proc [dbo].[SprptAssessmentCompartion_Subject]
#intQstnMasterID int,
#intAssessmentID int,
#intQstnMasterID1 int,
#intAssessmentID1 int,
#intUserID int
As
Begin
select DISTINCT vchSubject,intUserID,SUM(FrstId) as 'FrstId' ,SUM(ScndId) as 'ScndId' from
( SELECT
intSubjectID,
intUserID,
ISNULL([#intAssessmentID],0) as 'FrstId',
ISNULL([#intAssessmentID1],0) as 'ScndId',
FinalsCORE
FROM
(
select DISTINCT intSubjectID,intUserID,intAssignmnetID,SUM(KidTtl) as 'KidScore',COUNT(intSubjectID) AS 'FinalsCORE' ,(SUM(KidTtl) /COUNT(intSubjectID)*100) as 'Ct' from
(
select Answetble.vchAssignmentName ,intAssignmnetID,intUserID,intSlNo,isnull(QuiestionPaper.vchTopic,'-') as 'VchTopic',isnull(Answetble.fltMark,0) as 'KidTtl' ,QuiestionPaper.intSubjectID from QuiestionMapping
inner join QuiestionPaper on QuiestionPaper.intQstnID=QuiestionMapping.intQstnID
Left outer join
(
select distinct intQstnID,intAssessmentID,intAssignmnetID,intUserID,intQstnMasterID,fltMark,fltTotalMark,intAssignedByUserID,vchAssignmentName from
(
SELECT * from ManageAssessment
inner join Assignment ON Assignment.intAssignmnetID=ManageAssessment.intAssessmentID) as B
INNER JOIN UserMapping ON UserMapping.intPTUserID= intAssignedByUserID
where intQstnMasterID=#intQstnMasterID and intAssessmentID=#intAssessmentID AND intPTUserID=#intUserID
OR( intQstnMasterID=#intQstnMasterID1 and intAssessmentID=#intAssessmentID1 AND intPTUserID=#intUserID)
)
as Answetble on Answetble.intQstnID=QuiestionPaper.intQstnID
where QuiestionMapping.intQstnMasterID=#intQstnMasterID OR QuiestionMapping.intQstnMasterID=#intQstnMasterID1
)as A
GROUP BY intAssignmnetID,intSubjectID,intUserID
)
AS t
PIVOT
(
Max(Ct)
FOR intAssignmnetID IN( [#intAssessmentID] ,[#intAssessmentID1])
) AS p
)as B
inner join subject on Subject.intSubjectID=b.intSubjectID
group by subject.vchSubject,B.intUserID
End
Here #intAssessmentID is one of the columns when I use this in stored procedure I will get error
Msg 8114, Level 16, State 1, Procedure SprptAssessmentCompartion_Subject, Line 47
Error converting data type nvarchar to int.
Msg 473, Level 16, State 1, Procedure SprptAssessmentCompartion_Subject, Line 47
The incorrect value "#intAssessmentID" is supplied in the PIVOT operator.
Can anyone help me to resolve the error?
You cannot specify columns for PIVOT this way, you have to use dynamic SQL.
Create Proc [dbo].[SprptAssessmentCompartion_Subject]
#intQstnMasterID int,
#intAssessmentID int,
#intQstnMasterID1 int,
#intAssessmentID1 int,
#intUserID int
As
Begin
declare #sql as nvarchar(max) = N'select DISTINCT vchSubject,intUserID,SUM(FrstId) as ''FrstId'' ,SUM(ScndId) as ''ScndId'' from
( SELECT
intSubjectID,
intUserID,
ISNULL([' + CONVERT(NVARCHAR(20), #intAssessmentID) + N'],0) as ''FrstId'',
ISNULL([' + CONVERT(NVARCHAR(20), #intAssessmentID1) + N'],0) as ''ScndId'',
FinalsCORE
FROM
(
select DISTINCT intSubjectID,intUserID,intAssignmnetID,SUM(KidTtl) as ''KidScore'',COUNT(intSubjectID) AS ''FinalsCORE'' ,(SUM(KidTtl) /COUNT(intSubjectID)*100) as ''Ct'' from
(
select Answetble.vchAssignmentName ,intAssignmnetID,intUserID,intSlNo,isnull(QuiestionPaper.vchTopic,''-'') as ''VchTopic'',isnull(Answetble.fltMark,0) as ''KidTtl'' ,QuiestionPaper.intSubjectID from QuiestionMapping
inner join QuiestionPaper on QuiestionPaper.intQstnID=QuiestionMapping.intQstnID
Left outer join
(
select distinct intQstnID,intAssessmentID,intAssignmnetID,intUserID,intQstnMasterID,fltMark,fltTotalMark,intAssignedByUserID,vchAssignmentName from
(
SELECT * from ManageAssessment
inner join Assignment ON Assignment.intAssignmnetID=ManageAssessment.intAssessmentID) as B
INNER JOIN UserMapping ON UserMapping.intPTUserID= intAssignedByUserID
where intQstnMasterID=#intQstnMasterID and intAssessmentID=#intAssessmentID AND intPTUserID=#intUserID
OR( intQstnMasterID=#intQstnMasterID1 and intAssessmentID=#intAssessmentID1 AND intPTUserID=#intUserID)
)
as Answetble on Answetble.intQstnID=QuiestionPaper.intQstnID
where QuiestionMapping.intQstnMasterID=#intQstnMasterID OR QuiestionMapping.intQstnMasterID=#intQstnMasterID1
)as A
GROUP BY intAssignmnetID,intSubjectID,intUserID
)
AS t
PIVOT
(
Max(Ct)
FOR intAssignmnetID IN( [' + CONVERT(NVARCHAR(20), #intAssessmentID) + N'] ,[' + CONVERT(NVARCHAR(20), #intAssessmentID1) + N'])
) AS p
)as B
inner join subject on Subject.intSubjectID=b.intSubjectID
group by subject.vchSubject,B.intUserID'
exec sp_executesql #sql
End