Can we make join between two stored procedures in SQL Server - sql

I have this stored procedure:
CREATE PROCEDURE [dbo].[TestPackageAccept]
AS
BEGIN
SELECT A.Id,
a.PackageNumber,
a.Size,
a.Code,
a.TestPackageOrder,
B.status as LineCheckState,
B.ReportNumber as LineCheckReportNumber,
B.SubmitDateTime as LineCheckSubmitDateTime,
c.status as CleaningState,c.ReportNumber as CleanReportNumber,
c.SubmitDateTime as CleanSubmitDateTime,
c.status as ReInstatement,
d.ReportNumber as ReInstatementReportNumber,
d.SubmitDateTime as ReInstatementSubmitDateTime,
E.status as Flushing,
e.ReportNumber as FlushingReportNumber,
e.SubmitDateTime as FlushingSubmitDateTime,
f.status as Drying,
f.ReportNumber as DryingReportNumber,
f.SubmitDateTime as DryingSubmitDateTime,
m.status as PAD,
m.ReportNumber as PADReportNumber,
m.SubmitDateTime as PADSubmitDateTime,
n.status as Mono,
n.ReportNumber as MonoReportNumber,
n.SubmitDateTime as MonoSubmitDateTime,
p.status as Variation,
p.ReportNumber as VariationReportNumber,
p.SubmitDateTime as VariationSubmitDateTime
FROM TestPackages A
outer Apply (Select * from dbo.ReturnAcceptStepOfTestPackage(A.id,'LineCheck')) B
outer Apply (Select * from dbo.ReturnAcceptStepOfTestPackage(A.id,'Clean')) C
outer Apply (Select * from dbo.ReturnAcceptStepOfTestPackage(A.id,'Reinstatment'))D
outer Apply (Select * from dbo.ReturnAcceptStepOfTestPackage(A.id,'Flushing')) E
outer Apply (Select * from dbo.ReturnAcceptStepOfTestPackage(A.id,'Drying')) F
outer Apply (Select * from dbo.ReturnAcceptStepOfTestPackage(A.id,'Test')) G
outer Apply (Select * from dbo.ReturnAcceptStepOfTestPackage(A.id,'PADTest')) M
outer Apply (Select * from dbo.ReturnAcceptStepOfTestPackage(A.id,'Mono')) N
outer Apply (Select * from dbo.ReturnAcceptStepOfTestPackage(A.id,'Variation')) P
END;
And this
CREATE PROCEDURE [dbo].[TestPackageProgress]
AS
BEGIN
SELECT PackageId,
packagenumber,
count(*) as [Total],
sum(case [WeldStatus] when 'Accept' then 1 end) as Accept,
sum(case [WeldStatus] when 'accept' then 0 else 1 end) as Remain,
ROUND(CONVERT(float,sum(case [WeldStatus] when 'Accept' then 1 end))/CONVERT(float,count(*)) * 100,2) as PercentProgress
FROM [SPMS2].[dbo].[JointHistory]
WHERE PackageId is not null
GROUP BY PackageId,PackageNumber;
END;
Can I make a join between these two stored procedure's result sets on first.id = second.packageid?

You can put result sets from both SP into temp tables and then join them:
CREATE TABLE #PackageAccept (
Id INT,
PackageNumber INT,
Size INT,
Code NVARCHAR(100),
TestPackageOrder INT
--etc
--Here you add all columns from SP output with there datatypes
)
Then you can:
INSERT INTO #PackageAccept
EXEC [dbo].[TestPackageAccept]
The same way for second SP, then join:
SELECT *
FROM #PackageAccept pa
INNER JOIN #PackageProgress pp
ON pa.id = pp.packageid
Don't forget to DROP temp tables:
DROP TABLE #PackageAccept
DROP TABLE #PackageProgress
The full batch will be like:
IF OBJECT_ID(N'#PackageAccept') IS NOT NULL
BEGIN
DROP TABLE #PackageAccept
END
ELSE
BEGIN
CREATE TABLE #PackageAccept (
Id INT,
PackageNumber INT,
Size INT,
Code NVARCHAR(100),
TestPackageOrder INT
--etc
)
END
IF OBJECT_ID(N'#PackageProgress') IS NOT NULL
BEGIN
DROP TABLE #PackageProgress
END
ELSE
BEGIN
CREATE TABLE #P (
PackageId INT,
packagenumber INT,
[Total] INT,
Accept INT,
Remain INT
--etc
)
END
INSERT INTO #PackageAccept
EXEC [dbo].[TestPackageAccept]
INSERT INTO #PackageProgress
EXEC [dbo].[TestPackageProgress]
SELECT *
FROM #PackageAccept pa
INNER JOIN #PackageProgress pp
ON pa.id = pp.packageid

Related

Outer apply with INSERT statement

I want to do something like this
CREATE TABLE #tempFacilitiesAssociated
(
FacilityID BIGINT,
FacilityName VARCHAR(MAX),
IsPrimary BIT
)
-- Insert statements for procedure here
;WITH CTE_RESULT AS
(
SELECT
usr_id, t.name AS Title,
usr_fname, usr_lname, primaryAddress.add_suburb,
CASE
WHEN primaryAddress.add_suburb = #suburb THEN 1
WHEN t.name = #Title THEN 2
ELSE 3
END AS MatchOrder
FROM
core_users u
LEFT JOIN
RIDE_ct_title t ON t.title_id = u.usr_title
OUTER APPLY
(INSERT INTO #tempFacilitiesAssociated
EXEC dbo.[sp_Common_Get_AllFacilitiesForSupervisor] usr_id, 5
SELECT TOP 1 fa.*
FROM CORE_Facilities f
LEFT JOIN CORE_FacilityAddresses fa ON fac_id = fa.add_owner
WHERE fac_id = (SELECT TOP 1 FacilityID
FROM #tempFacilitiesAssociated
WHERE IsPrimary = 1)) primaryAddress
WHERE
u.usr_fname = #FirstName AND usr_lname = #LastName
)
So, first I want to get all facilities of that user through a stored procedure, and then use it to outer apply and select its suburb
UPDATE
I tried using function instead
CREATE FUNCTION fn_GetAddressForUserFacility
(#UserID BIGINT)
RETURNS #Address TABLE (FacilityID BIGINT,
add_address NVARCHAR(MAX),
add_addressline2 NVARCHAR(MAX),
add_suburb NVARCHAR(MAX)
)
AS
BEGIN
DECLARE #FacilitiesAssociated TABLE
(FacilityID BIGINT,
FacilityName NVARCHAR(MAX),
IsPrimary BIT)
INSERT INTO #FacilitiesAssociated
EXEC dbo.[sp_Common_Get_AllFacilitiesForSupervisor] #UserID, 5
INSERT INTO #Address
SELECT TOP 1
fa.add_owner, fa.add_address, fa.add_addressline2, fa.add_suburb
FROM
CORE_Facilities f
LEFT JOIN
CORE_FacilityAddresses fa ON f.fac_id = fa.add_owner AND add_type = 5
WHERE
fac_id = (SELECT TOP 1 FacilityID
FROM #FacilitiesAssociated
WHERE IsPrimary = 1)
RETURN
END
But now its returning
Invalid use of a side-effecting operator 'INSERT EXEC' within a function.

Returning column with count of 0

I have a query that looks up a list of documents depending on their department and their status.
DECLARE #StatusIds NVARCHAR(MAX) = '1,2,3,4,5';
DECLARE #DepartmentId NVARCHAR(2) = 'IT';
SELECT ILDPST.name,
COUNT(*) AS TodayCount
FROM dbo.TableA ILDP
LEFT JOIN dbo.TableB ILDPS ON ILDPS.IntranetLoanDealPreStateId = ILDP.IntranetLoanDealPreStateId
LEFT JOIN dbo.TableC ILDPST ON ILDPST.IntranetLoanDealPreStateTypeId = ILDPS.CurrentStateTypeId
WHERE (ILDP.CreatedByDepartmentId = #DepartmentId OR #DepartmentId IS NULL)
AND ILDPS.CurrentStateTypeId IN (
SELECT value
FROM dbo.StringAsIntTable(#StatusIds)
)
GROUP BY ILDPST.name;
This returns the results:
However, I'd also like to be able to return statuses where the TodayCount is equal to 0 (i.e. any status with an id included in #StatusIds should be returned, regardless of TodayCount).
I've tried messing with some unions / joins / ctes but I couldn't quite get it to work. I'm not much of an SQL person so not sure what else to provide that could be useful.
Thanks!
If you want to have all the records from TableC you need to left join all other tables to it, not left join it to the other tables. Also it's best to INNER JOIN the filtering table you create from #StatusIds rather then apply it through INclause. Try this:
DECLARE #StatusIds NVARCHAR(MAX) = '1,2,3,4,5';
DECLARE #DepartmentId NVARCHAR(2) = 'IT';
SELECT ILDPST.Name, COUNT(ILDP.IntranetLoanDealPreStateId) AS TodayCount
FROM (SELECT DISTINCT value FROM dbo.StringAsIntTable(#StatusIds)) StatusIds
INNER JOIN dbo.TableC ILDPST
ON ILDPST.IntranetLoanDealPreStateTypeId = StatusIds.value
LEFT JOIN dbo.TableB ILDPS
ON ILDPS.CurrentStateTypeId = ILDPST.IntranetLoanDealPreStateTypeId
LEFT JOIN dbo.TableA ILDP
ON ILDP.IntranetLoanDealPreStateId = ILDPS.IntranetLoanDealPreStateId
AND (ILDP.CreatedByDepartmentId = #DepartmentId OR #DepartmentId IS NULL)
GROUP BY ILDPST.Name;
Try this instead:
DECLARE #StatusIds NVARCHAR(MAX) = '1,2,3,4,5';
DECLARE #DepartmentId NVARCHAR(2) = 'IT';
SELECT ILDPST.name,
COUNT(ILDP.IntranetLoanDealPreStateId) AS TodayCount
FROM
dbo.TableC ILDPST
LEFT JOIN
dbo.TableB ILDPS ON ILDPST.IntranetLoanDealPreStateTypeId = ILDPS.CurrentStateTypeId
LEFT JOIN
dbo.TableA ILDP ON ILDPS.IntranetLoanDealPreStateId = ILDP.IntranetLoanDealPreStateId
AND (ILDP.CreatedByDepartmentId = #DepartmentId OR #DepartmentId IS NULL)
WHERE
ILDPST.IntranetLoanDealPreStateTypeId
IN (
SELECT value
FROM dbo.StringAsIntTable(#StatusIds)
)
GROUP BY ILDPST.name;
You could use the following function to create a table value for your status id's.
CREATE FUNCTION [dbo].[SplitString]
(
#myString varchar(max),
#deliminator varchar(2)
)
RETURNS
#ReturnTable TABLE
(
[Part] [varchar](max) NULL
)
AS
BEGIN
Declare #iSpaces int
Declare #part varchar(max)
--initialize spaces
Select #iSpaces = charindex(#deliminator,#myString,0)
While #iSpaces > 0
Begin
Select #part = substring(#myString,0,charindex(#deliminator,#myString,0))
Insert Into #ReturnTable(Part)
Select #part
Select #myString = substring(#mystring,charindex(#deliminator,#myString,0)+ len(#deliminator),len(#myString) - charindex(' ',#myString,0))
Select #iSpaces = charindex(#deliminator,#myString,0)
end
If len(#myString) > 0
Insert Into #ReturnTable
Select #myString
RETURN
END
This can now be used as a table that you can LEFT JOIN to.
DECLARE #StatusIds NVARCHAR(MAX) = '1,2,3,4,5';
SELECT * FROM dbo.SplitString(#StatusIds, ',')
It is not tested but give it a try:
;With Cte ( Value ) As
( Select Distinct Value From dbo.StringAsIntTable( #StatusIds ) )
Select
ILDPST.name,
COUNT(*) AS TodayCount
From
dbo.TableC As ILDPST
Inner Join Cte On ( ILDPST.IntranetLoanDealPreStateTypeId = Cte.Value )
Left Join dbo.TableB As ILDPS On ( ILDPST.IntranetLoanDealPreStateTypeId = ILDPS.CurrentStateTypeId )
Left Join dbo.TableA As ILDP On ( ILDPS.IntranetLoanDealPreStateId = ILDP.IntranetLoanDealPreStateId )
And ( ( ILDP.CreatedByDepartmentId = #DepartmentId ) Or ( #DepartmentId Is Null ) )
Group By
ILDPST.name

error in IF ELSE statement in SQL [duplicate]

This question already has an answer here:
Drop temp table within IF ELSE statement
(1 answer)
Closed 7 years ago.
I have the following stored procedure, But seems like the #Temp table is creating troubles in it. I get following error
There is already an object named '#Temp' in the database.
I guess somethings wrong with my IF ELSE
Here is the stored procedure:
create procedure spGetHOSalesReport
#DateFrom datetime,#DateTo datetime,#EmbossLine varchar(20),#CountryID int,#status char(2)
AS
Set #DateTo = #DateTo +1
if(#status = 'E1')
begin
Select PT.[ID] 'TransactionID', PT.BatchNumber, PT.SequenceNumber, PT.TransactionDate,
PT.TerminalID, PT.TotalAmount, PT.TransactionTypeID, TT.TransactionType,PT.PAN 'EmbossLine',PT.PreBalanceAmount, PT.PostBalanceAmount, RefTxnID, SettlementDate,PaidCash, CreditAmount, DiscountAmount,
RefPAN, PT.Remarks, ' ' + CashierCard as 'SupervisorCard',St.StoreID
into #Temp
from TempPOS_Transactions PT inner join TransactionType TT on TT.TransactionTypeID = PT.TransactionTypeID
inner join Staff St on St.CardNumber=PT.CashierCard
where
PT.[ID] not in (Select distinct isnull(TransactionID,0) from Testcards)
and (PT.TransactionDate >= #DateFrom) and (PT.TransactionDate < #DateTo)
and (PT.TransactionTypeID = 6) and (PT.BatchNumber = 0) and (Pt.SequenceNumber =-1)
select T.*, ' '+ C.EmbossLine+' ' as 'EmbossLine', C.EmbossLine as 'EmbossLine1',
isnull(C.FirstName,'') +' '+ isnull(C.LastName,'') 'EmbossName',C.FirstName,C.LastName,City.CityName,Country.CountryName,Country.CurrencyName, PM.MerchantID, PM.MerchantName1, C.AccountNumber, C.VehicleNumber, C.ExpiryDate ,
case C.Status when 'E0' then 'Authorized' when 'E1' then 'Pending' end 'Status'
from #Temp T
inner join Card C on C.EmbossLine= T.EmbossLine
inner join Terminal on Terminal.TerminalID = T.TerminalID
inner join Merchant PM on PM.MerchantID = Terminal.MerchantID
inner join City on City.CityID = PM.CityID
inner join Country on Country.CountryID = PM.CountryID
where C.Status <>'E3'
and C.CardID not in (Select distinct isnull(CardID,0) from Testcards)
and (C.EmbossLine like '%'+#EmbossLine+'%' or #EmbossLine like '-999')
and (PM.CountryID = #CountryID or #CountryID ='-999')
and (C.Status = #status)
order by T.TransactionDate, MerchantName1, T.BatchNumber, T.SequenceNumber
End
Else
Begin
Select PT.[ID] 'TransactionID', PT.BatchNumber, PT.SequenceNumber, PT.TransactionDate,
PT.TerminalID, PT.TotalAmount, PT.TransactionTypeID, TT.TransactionType,PT.PAN 'EmbossLine',PT.PreBalanceAmount, PT.PostBalanceAmount, RefTxnID, SettlementDate,PaidCash, CreditAmount, DiscountAmount,
RefPAN, PT.Remarks, ' ' + CashierCard as 'SupervisorCard',St.StoreID
into #Temp
from POS_Transactions PT inner join TransactionType TT on TT.TransactionTypeID = PT.TransactionTypeID
inner join Staff St on St.CardNumber=PT.CashierCard
where PT.[ID] not in (Select distinct isnull(TransactionID,0) from Testcards) and (PT.TransactionDate >= #DateFrom) and (PT.TransactionDate < #DateTo)
and (PT.TransactionTypeID = 6) and (PT.BatchNumber = 0) and (Pt.SequenceNumber =-1)
select T.*, ' '+ C.EmbossLine+' ' as 'EmbossLine', C.EmbossLine as 'EmbossLine1',
isnull(C.FirstName,'') +' '+ isnull(C.LastName,'') 'EmbossName',C.FirstName,C.LastName,City.CityName,Country.CountryName,Country.CurrencyName, PM.MerchantID, PM.MerchantName1, C.AccountNumber, C.VehicleNumber, C.ExpiryDate ,
case C.Status when 'E0' then 'Authorized' when 'E1' then 'Pending' end 'Status'
from #Temp T
inner join Card C on C.EmbossLine= T.EmbossLine
inner join Terminal on Terminal.TerminalID = T.TerminalID
inner join Merchant PM on PM.MerchantID = Terminal.MerchantID
inner join City on City.CityID = PM.CityID
inner join Country on Country.CountryID = PM.CountryID
where C.Status <>'E3'
and C.CardID not in (Select distinct isnull(CardID,0) from Testcards)
and (C.EmbossLine like '%'+#EmbossLine+'%' or #EmbossLine like '-999')
and (PM.CountryID = #CountryID or #CountryID ='-999')
and (C.Status = #status)
order by T.TransactionDate, MerchantName1, T.BatchNumber, T.SequenceNumber
End
drop table #Temp
You cannot have two statements in the same procedure that creates a temp table with the same name. This is a leftover from SQL 6.5 which did not have deferred name resolution.
And in any case, it only makes sense if the tables are created exactly the same, else your procedure will behave very funky.
So instead of using SELECT INTO, use CREATE TABLE + INSERT.
UPDATE
According to the selected way from comment:
Second option: First create temp table and insert
First let's create the temp table. For that you should modify your procedure like:
create procedure spGetHOSalesReport
#DateFrom datetime,#DateTo datetime,#EmbossLine varchar(20),#CountryID int,#status char(2)
AS
BEGIN -- begin procedure
SET #DateTo = #DateTo +1
if object_id('tempdb..#Temp') is not null drop table #Temp
create table #Temp
( TransactionID int
, BatchNumber ... ( your type of field )
, SequenceNumber ...
, TransactionDate ...
, TerminalID int
, TotalAmount ...
, TransactionTypeID int
, TransactionType ...
, EmbossLine ...
, PreBalanceAmount ...
, PostBalanceAmount ...
, RefTxnID int
, SettlementDate ...
, PaidCash ...
, CreditAmount ...
, DiscountAmount ...
, RefPAN ...
, Remarks ...
, SupervisorCard ...
, StoreID int
)
if(#status = 'E1')
.......
I do not know which data type has these fields, so, you have to do yourself. Then edit insert into temp table in first case and similar in another case:
insert into #Temp
Select PT.[ID] 'TransactionID', PT.BatchNumber, PT.SequenceNumber, PT.TransactionDate,
PT.TerminalID, PT.TotalAmount, PT.TransactionTypeID, TT.TransactionType,PT.PAN 'EmbossLine',PT.PreBalanceAmount, PT.PostBalanceAmount, RefTxnID, SettlementDate,PaidCash, CreditAmount, DiscountAmount,
RefPAN, PT.Remarks, ' ' + CashierCard as 'SupervisorCard',St.StoreID
from TempPOS_Transactions PT inner join TransactionType TT on TT.TransactionTypeID = PT.TransactionTypeID
inner join Staff St on St.CardNumber=PT.CashierCard
where ...
In the end of procedure you can add:
End -- end of your if
if object_id('tempdb..#Temp') is not null drop table #Temp
END -- end of procedure
But the simplest way is create two different temp tables:
if(#status = 'E1')
begin
if object_id('tempdb..#Temp1') is not null drop table #Temp1
Select PT.[ID] 'TransactionID', PT.BatchNumber, ...
into #Temp1
from TempPOS_Transactions PT
inner join TransactionType TT on TT.TransactionTypeID = PT.TransactionTypeID
.....
end
else
begin
if object_id('tempdb..#Temp2') is not null drop table #Temp2
Select PT.[ID] 'TransactionID', PT.BatchNumber, ...
into #Temp2
from POS_Transactions PT
inner join TransactionType TT on TT.TransactionTypeID = PT.TransactionTypeID
....
end
Also, you can write just two select without creating temp table in this case

Loop the select statement in sql server stored procedure

I created a store procedure shown below
CREATE PROCEDURE [dbo].[sp_rptlabelPrint] --'HKOHBLAE11/0007' ,'','HKO'
(
#Code varchar(25),
#Format int=0 ,
#Branch varchar(25)=''
)
AS
SELECT
HB.HB_cCode as HBCode,
HB.MB_cCode as MBCode,
PO.PO_cShortName as Dest,
PS.PO_cShortName as Source
FROM
SHI_HOUSEBLHDR HB
left join SHI_PORTS PO on HB.PO_cDischargePortCode = PO.PO_cCode
left join SHI_PORTS PS on HB.PO_cLoadPortCode = PS.PO_cCode
where HB.HB_cCode=#Code and HB.br_ccode=#Branch
Here it reurns a single row.
But i need to pass a integer value to parameter #Format and if it set to 2 the select statement must execute 2 times and returns the two rows. If its set 4 it returns 4 times of the same row. is it possible to loop the select statement and return the rows
You can use a temp table to store and return the result
ALTER PROCEDURE [dbo].[sp_rptlabelPrint]
(
#Code varchar(25),
#Format int=0 ,
#Branch varchar(25)=''
)
AS
CREATE TABLE #MyTempTable(HBCode VARCHAR(25),MBCode VARCHAR(25),Dest VARCHAR(25),Source VARCHAR(25))
WHILE (#Format < 4)
BEGIN
insert INTO #MyTempTable
SELECT
HB.HB_cCode as HBCode,
HB.MB_cCode as MBCode,
PO.PO_cShortName as Dest,
PS.PO_cShortName as Source
FROM
SHI_HOUSEBLHDR HB
left join SHI_PORTS PO on HB.PO_cDischargePortCode = PO.PO_cCode
left join SHI_PORTS PS on HB.PO_cLoadPortCode = PS.PO_cCode
where HB.HB_cCode=#Code and HB.br_ccode=#Branch
Set #Format = #Format + 1
END
SELECT * FROM #MyTempTable
Write as:
CREATE PROCEDURE [dbo].[sp_rptlabelPrint] --'HKOHBLAE11/0007' ,'','HKO'
(
#Code varchar(25),
#Format int=0 ,
#Branch varchar(25)=''
)
AS
SELECT
HB_cCode as HBCode,
MB_cCode as MBCode,
PO_cShortName as Dest,
PO_cShortName as Source
FROM
(
SELECT
HB.HB_cCode as HBCode,
HB.MB_cCode as MBCode,
PO.PO_cShortName as Dest,
PS.PO_cShortName as Source
FROM
SHI_HOUSEBLHDR HB
left join SHI_PORTS PO on HB.PO_cDischargePortCode = PO.PO_cCode
left join SHI_PORTS PS on HB.PO_cLoadPortCode = PS.PO_cCode
where HB.HB_cCode=#Code and HB.br_ccode=#Branch
)T
Cross JOIN
(
SELECT TOP ( #Format ) ROW_NUMBER()
OVER (ORDER BY s1.[object_id])
FROM sys.all_objects AS s1
CROSS JOIN sys.all_objects AS s2
) AS x(n) ;

SP executing error

I am writing below SP.But when i try to run this query i am getting this error:
There is already an object named
'#myCourses1' in the database.
So this getting in two else loops. also
create proc [dbo].[GetOrdersByUserIDwithSubscription]
(
#UserID int
)
as
begin
declare #status varchar(500)
declare #substatus char(2)
select #substatus=Subscribe_status from tbl_user where userid=#userid
print #substatus
if #substatus='N'
BEGIN
select a.*, b.CategoryText, Cast('' as Varchar(10)) as SectionsViewed, PurchasedDate as dateadded into #myCourses1 from dbo.Tbl_CourseInformations a JOIN Tbl_Categories b ON a.AssignCategory = b.CategoryID
Join Tbl_Orders c ON c.UserID = #UserID and c.CourseID = a.CourseID and c.courseprice<>'subscriber'
Order By CategoryText, CourseTitle
END
else if #substatus=''
BEGIN
select a.*, b.CategoryText, Cast('' as Varchar(10)) as SectionsViewed, PurchasedDate as dateadded into #myCourses1 from dbo.Tbl_CourseInformations a JOIN Tbl_Categories b ON a.AssignCategory = b.CategoryID
Join Tbl_Orders c ON c.UserID = #UserID and c.CourseID = a.CourseID and c.courseprice<>'subscriber'
Order By CategoryText, CourseTitle
END
else if #substatus='Y'
BEGIN
select a.*, b.CategoryText, Cast('' as Varchar(10)) as SectionsViewed, PurchasedDate as dateadded into #myCourses1 from dbo.Tbl_CourseInformations a JOIN Tbl_Categories b ON a.AssignCategory = b.CategoryID
Join Tbl_Orders c ON c.UserID = #UserID and c.CourseID = a.CourseID
Order By CategoryText, CourseTitle
END
The SQL Parser is choking because you have used the same temp table name in different parts of the IF statement. The IF does not have scope like other programming languages.
If you do not need to reference the temp table outside of each of the IF blocks you can get around the problem by using a different table name in each part.
Have a look at my answer to a similar question.
Also, the monstrocity of a query you have could be reduced to this:
create proc [dbo].[GetOrdersByUserIDwithSubscription](
#UserID int
)
as
begin
declare #substatus char(2)
select #substatus = Subscribe_status
from tbl_user
where userid = #userid
select a.*, b.CategoryText,
Cast("" as Varchar(10)) as SectionsViewed,
PurchasedDate as dateadded
from dbo.Tbl_CourseInformations a
join Tbl_Categories b ON a.AssignCategory = b.CategoryID
join Tbl_Orders c ON c.UserID = #UserID
and c.CourseID = a.CourseID
and (#substatus = 'N' or c.courseprice <> 'subscriber')
order by CategoryText, CourseTitle
END
Explicitly create the temp table at the beginning of the proc.
CREATE TABLE #myCourses1 (
...
)
Then write your SELECT statements as:
INSERT INTO #myCourses1
select a.*, b.CategoryText, Cast('' as Varchar(10)) as SectionsViewed, PurchasedDate as dateadded
from dbo.Tbl_CourseInformations
...
You syntax is
SELECT [Column-List] INTO #TempTable FROM [Rest-of-Query]
When using this syntax, Sql Server attempts to create #TempTable on the fly based on your column list (source).
To get around this, either Drop #TempTable at the beginning of the stored procedure (if you do not need its data beyond the scope of the SP), or make it a permanent table.