Order By Statement - sql

I want to order the Time in ASC for the below query. I tried adding ORDER BY after WHERE clause but can't get the result as join statements are used. I have added the full sql query here.
ALTER PROCEDURE [dbo].[USP_GetFlightInfo]
(
#Origin NVARCHAR(50)=null,
#Destination NVARCHAR(50)=null,
#FlightNo NVARCHAR(50)= null
)
AS
BEGIN
SET NOCOUNT ON;
IF #FlightNo IS NULL
(
SELECT tfs.FlightNo,tfs.Origin,tfs.Destination,tfs.[Time],tfs.RevisedTime,tfSSS.DescriptionName, tfSS.FlightStatus from tblFlightSchedule tfs
INNER JOIN tblFlightStatus tfSS ON tfs.FSId= tfSS.FSId
LEFT OUTER JOIN tblFlightStatusDescription tfSSS ON tfSSS.FSDId= tfs.FSDId
where tfs.Origin=#Origin and tfs.Destination =#Destination
ORDER BY tfs.[Time];
)
ELSE IF #FlightNo IS NOT NULL
(
SELECT tfs.FlightNo,tfs.Origin,tfs.Destination,tfs.[Time],tfs.RevisedTime,tfSSS.DescriptionName, tfSS.FlightStatus from tblFlightSchedule tfs
INNER JOIN tblFlightStatus tfSS ON tfs.FSId= tfSS.FSId
LEFT OUTER JOIN tblFlightStatusDescription tfSSS ON tfSSS.FSDId= tfs.FSDId
where tfs.Origin=#Origin and tfs.Destination =#Destination and tfs.FlightNo=#FlightNo and tfs.FlightNo =#FlightNo
ORDER BY tfs.[Time];
)
END

Just put:
SELECT tfs.FlightNo,tfs.Origin,tfs.Destination,tfs.[Time],tfs.RevisedTime,
tfSSS.DescriptionName, tfSS.FlightStatus
FROM tblFlightSchedule tfs
INNER JOIN tblFlightStatus tfSS ON tfs.FSId= tfSS.FSId
LEFT OUTER JOIN tblFlightStatusDescription tfSSS ON tfSSS.FSDId= tfs.FSDId
WHERE tfs.Origin=#Origin and
tfs.Destination =#Destination and
(
tfs.FlightNo =#FlightNo or
#FlightNo is null
)
ORDER BY tfs.[Time];
As the code inside your stored procedure. No need for the IF and duplicating the query.
The main issue in your existing code is that SQL Server uses BEGIN and END to enclose blocks of code - not brackets (). So an IF should look like:
IF <Something>
BEGIN
--If block
END
ELSE
BEGIN
--Else block
END

Related

SQL Code working in SSMS but not in Report Builder 3.0

I have a code that works in SSMS but not in Report Builder. Tn the first part I create a temporary table and in the second i attach that table (using join) to my entire query. In SSMS i can do it declaring twice the parameters and using GO after the temporary table is created but RP Builder i cannot use go.
Below you can find the code.
Any hint is appreciated. Thank you!
IF OBJECT_ID('tempdb..#TempResTable') IS NOT NULL DROP TABLE #TempResTable
IF OBJECT_ID('tempdb..#Temp123') IS NOT NULL DROP TABLE #Temp123
declare #fromDate date
set #fromDate='2015-10-26'
declare #toDate date
set #toDate='2015-11-17'
Create table #tempResTable (id_resource int, Mins int)
while (#fromDate <= #toDate)
begin
Insert into #TempResTable
select
r.id_resource
,datediff(mi,coalesce(cw.from_time,convert(time, '12:00:00 AM')),coalesce(cw.till_time,convert(time , '23:59:59 PM'))) as 'MinutesAvailable'
from calendar
join resource r on r.id_calendar=calendar.id_calendar
left join calendarVersion cv on cv.id_calendarVersion=calendar.id_calendar
left join calendarweekdayentry cw on cw.id_calendarVersion=cv.id_calendarVersion
--where r.id_resource=#resource
where cw.id_availabilitykind in(2,8)
and cw.weekday=(case when (datediff(dd,cv.from_date,#fromDate)+1)-((datediff(dd,cv.from_date,#fromDate)+1)/(nofweeks*7)*(nofweeks*7))=0 then nofweeks*7
else (datediff(dd,cv.from_date,#fromDate)+1)-((datediff(dd,cv.from_date,#fromDate)+1)/(nofweeks*7)*(nofweeks*7))
end)
Group By r.id_resource
,cv.from_date
,cw.from_time
,cw.till_time,cw.id_availabilitykind
--)
set #fromDate=dateadd(dd,1,#fromDate)
end
go
declare #fromDate date
set #fromDate='2015-10-26'
declare #toDate date
set #toDate='2015-11-17'
select * into #temp123 from
(
select vwdepartment.departmentName
,row_number() over (order by resource.ID_resource) as 'rowNumber'
,resource.resourceName
,resource.id_resource
,B.AvailabilityHours
--,vwplannedShift.id_shift
--,vwplannedShift.plannedstartinstant
--,vwplannedShift.plannedfinishinstant
--,datediff(mi,vwplannedShift.plannedstartinstant,vwplannedShift.plannedfinishinstant)
, ( select sum(distinct(datediff(mi,vwplannedShift.plannedstartinstant,vwplannedShift.plannedfinishinstant))) from resource r1 where r1.resourceName=resource.resourceName group by r1.resourceName ) as 'MinsPlanned'
--,cw.from_time
--,cw.till_time
--,[dbo].[sp_ResourceAvailability]
from vwplannedShift
join vwshift on vwshift.id_shift = vwplannedShift.id_shift
and datediff(dd,#fromDate , vwplannedShift.plannedStartInstant) >=0
and datediff(dd,#toDate , vwplannedShift.plannedStartInstant) <=0
join vwdepartment on vwdepartment.id_department = vwplannedShift.id_department
join vwaction actions on coalesce(actions.t3_shift, actions.id_shift) = vwshift.id_shift
join vwresourceCombinationDriver driver on actions.id_unionResourceCombi = driver.id_resourceCombination
join resource on driver.id_resource = resource.id_resource
join resourceKind rk on rk.id_resourceKind=resource.id_resourceKind
join calendar c on c.id_calendar=resource.id_calendar
join calendarversion cv on cv.id_calendar=c.id_calendar
join calendarweekdayentry cw on cw.id_calendarVersion=cv.id_calendarVersion
left join availabilityKind ak on ak.id_availabilityKind=cw.id_availabilityKind and cw.id_availabilityKind in (2,8)
LEFT JOIN (select id_resource, sum(mins)AS AvailabilityHours from #tempResTable GROUP BY #tempResTable.id_resource) B ON B.ID_RESOURCE=RESOURCE.ID_RESOURCE
group by resource.resourcename,resource.id_resource,vwdepartment.departmentName,B.AvailabilityHours
union
select vwdepartment.departmentName
,row_number() over (order by resource.ID_resource) as 'rowNumber'
,resource.resourceName
,resource.id_resource
,B.AvailabilityHours
--,vwplannedShift.id_shift
--,vwplannedShift.plannedstartinstant
--,vwplannedShift.plannedfinishinstant
--,datediff(mi,vwplannedShift.plannedstartinstant,vwplannedShift.plannedfinishinstant)
,( select sum(distinct(datediff(mi,vwplannedShift.plannedstartinstant,vwplannedShift.plannedfinishinstant))) from resource r1 where r1.resourceName=resource.resourceName group by r1.resourceName ) as 'MinsPlanned'
--,cw.from_time
--,cw.till_time
from vwplannedShift
join vwshift on vwshift.id_shift = vwplannedShift.id_shift
and datediff(dd,#fromdate , vwplannedShift.plannedStartInstant) >=0
and datediff(dd,#todate , vwplannedShift.plannedStartInstant) <=0
join vwdepartment on vwdepartment.id_department = vwplannedShift.id_department
join vwaction actions on coalesce(actions.t3_shift, actions.id_shift) = vwshift.id_shift
join vwresourcecombinationtruck truck on actions.id_unionResourceCombi = truck.id_resourceCombination
join resource on truck.id_resource = resource.id_resource
join resourceKind rk on rk.id_resourceKind=resource.id_resourceKind
left join calendar c on c.id_calendar=resource.id_calendar
left join calendarversion cv on cv.id_calendar=c.id_calendar
left join calendarweekdayentry cw on cw.id_calendarVersion=cv.id_calendarVersion
left join availabilityKind ak on ak.id_availabilityKind=cw.id_availabilityKind and cw.id_availabilityKind in (2,8)
LEFT JOIN (select id_resource, sum(mins)AS AvailabilityHours from #tempResTable GROUP BY #tempResTable.id_resource) B ON B.ID_RESOURCE=RESOURCE.ID_RESOURCE
group by resource.resourcename,resource.id_resource,vwdepartment.departmentName,B.AvailabilityHours
) as cte
select* from #temp123
Quoting from the documentation on GO:
GO is not a Transact-SQL statement; it is a command recognized by the sqlcmd and osql utilities and SQL Server Management Studio Code editor.
So not recognized by Report Builder.
While TT has identified the problem with the code you have, the workaround would be to create a new Stored Procedure in the database, which will allow you to create, populate and interrogate temporary tables at will.
Something like this perhaps?
CREATE PROCEDURE [dbo].[GetMyData] ( #startDate DATETIME, #endDate DATEIME )
Create table #tempResTable (id_resource int, Mins int)
...
(All the rest of your code (without the variable declarations and 'GOs')
...
select* from #temp123
GO
GRANT EXECUTE ON [dbo].[GetMyData] TO [MyUser]
GO
Then reference this directly from your Dataset by choosing "Stored Procedure" instead of "Text"

Function with in clause in where condition of SP decreasing the procedure performance

I have a procedure that has following functions in where condition:
select col1,col2,col3...
from table1
where
(dbo.GetFilStatus(et.SgDate,et.Speed,(SELECT COUNT(J.JId) FROM tbl_Nt J
inner JOIN tbl_NAssign JN ON JN.NNo =J.NNo
inner JOIN dbo.tbl_CStatus JS ON JS.CStatusID=J.CStatusID
INNER JOIN dbo.tbl_SStatus ss ON ss.SStatusID=JS.SStatusID
WHERE JN.DriID=et.DriID AND ss.SStatusID !=9),et.IgStatus)
in (Select val from Split('A,B,C,D,E',',')))
)
getfilstatus status contains the following code:-
if (#ServerDatetime <= DATEADD(MI,-10, GETDATE()))
BEGIN
IF(#xIgStatus = 'ON')
BEGIN
set #FilStatus= 'NoSignal'
END
ELSE
BEGIN
set #FilStatus= 'Stopped'
end
End
else IF(#xIgStatus = 'ON')
Begin
if(#Speed>5)
begin
if(#JCount<=0)
set #FilStatus='Moving'
else
set #FilStatus='Working'
end
else
begin
set #FilStatus= 'Idle'
end
End
else
Begin
set #FilStatus= 'Stopped'
end
RETURN #FilStatus
GetFilStatus always returns more than 10000 records. Sometimes its more than 100000. Its slowing the final output of query. Currently its taking more than 2 mins to return the output.
I am searching for any other option or any other trick using which the query performance can be increased and I could get the output in seconds.
Any suggestions? Any ideas?
It is better to put the split items in a temp table, as the split function needs to execute each time in the query iterations.
The third parameter has a complex inline query, i have created a temp table for the subset data and filtered necessary data inline.
SELECT S.items AS value
INTO #splited_items
FROM Split('A,B,C,D,E', ',') S;
SELECT Count(J.jid) AS Count_JId,
JN.driid AS DriID
INTO #joined_table
FROM tbl_nt J
INNER JOIN tbl_nassign JN
ON JN.nno = J.nno
INNER JOIN dbo.tbl_cstatus JS
ON JS.cstatusid = J.cstatusid
INNER JOIN dbo.tbl_sstatus ss
ON ss.sstatusid = JS.sstatusid
WHERE ss.sstatusid != 9
GROUP BY JN.driid
SELECT col1,
col2,
col3... from table1
WHERE ( dbo.Getfilstatus(et.sgdate, et.speed, (SELECT count_jid
FROM #joined_table
WHERE driid = et.driid),
et.igstatus)
IN (SELECT value
FROM #splited_items) )

Issue In Sql Stored Procedure

In the below sql query When i execute it with some values in where condition it displays data and if i place values in [Sp_GrnValuationReportV1]--1,'GR140000001','GR140000009','2014-10-11','2014-12-25' it is display no data.Please help me to solve the issue.
ALTER PROCEDURE [dbo].[Sp_GrnValuationReportV1] --1,'GR140000001','GR140000009','2014-10-11','2014-12-25'
-- Add the parameters for the stored procedure here
#i_LocationID int,
#i_GrnStartNo varchar,
#i_GrnEndNo varchar,
#d_StartDate DATE,
#d_EndDate DATE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT DISTINCT GRN.GoodsReceivedNoteNo,GRN.LocationID,GRN.CreatedOn,PO.PurchaseOrderNo,V.VendorName,
GRN.SupplierInvoiceNo,GRN.SupplierInvoiceDate,SR.LRNO,T.TransporterName,
CASE
WHEN Count(GRND.GoodsReceivedNoteID) OVER(partition BY GRND.GoodsReceivedNoteID) > 1
THEN Isnull(( GRND.FreightCharges ), 0.00)
ELSE Isnull(( OEC.FreightCharges ), 0.00)
END FreightCharge,CASE
WHEN Count(GRND.GoodsReceivedNoteID) OVER(partition BY GRND.GoodsReceivedNoteID) > 1
THEN Isnull(( GRND.LoadingCost + GRND.UnloadingCost ), 0.00)
ELSE Isnull(( OEC.LoadingCost + OEC.UnloadingCost ), 0.00)
END LoadingandUnloadingcharges ,
P.ProductCode,P.ProductName,GRND.ReceivedQuantity,GRND.RejectedQuantity,GRND.AcceptedQuantity,
GRND.UnitPrice AS BasicRate,ISNULL( (GRND.UnitPrice*GRND.ReceivedQuantity),0.00) BasicValue,GRND.VAT,CASE
WHEN Count(GRND.GoodsReceivedNoteID) OVER(partition BY GRND.GoodsReceivedNoteID) > 1
THEN Isnull(( GRND.FreightCharges ), 0.00)
ELSE Isnull(( OEC.FreightCharges ), 0.00)
END FreightApportioned,
CASE
WHEN Count(GRND.GoodsReceivedNoteID) OVER(partition BY GRND.GoodsReceivedNoteID) > 1
THEN Isnull(( GRND.LoadingCost + GRND.UnloadingCost ), 0.00)
ELSE Isnull(( OEC.LoadingCost + OEC.UnloadingCost ), 0.00)
END LoadingandUnloadingApportioned,ISNULL((GRND.UnitPrice+OEC.FreightCharges+OEC.LoadingCost+OEC.UnloadingCost),0.00)AS TotalCost
FROM GoodsReceivedNoteDetail GRND
LEFT OUTER JOIN GoodsReceivedNote GRN ON GRN.GoodsReceivedNoteID=GRND.GoodsReceivedNoteID
LEFT OUTER JOIN PurchaseOrder PO ON PO.PurchaseOrderID=GRN.PurchaseOrderID
LEFT OUTER JOIN Vendor V ON V.VendorID=PO.VendorID
LEFT OUTER JOIN SecurityRegister SR ON SR.SecurityRegisterID=GRN.SecurityRegisterID
LEFT OUTER JOIN Transporter T ON T.TransporterID=SR.TransporterID
LEFT OUTER JOIN OtherExpenseCost OEC ON OEC.GoodsReceivedNoteID=GRN.GoodsReceivedNoteID
LEFT OUTER JOIN Product P ON P.ProductID=GRND.ProductID
--WHERE GRN.LocationID=#i_LocationID AND GRN.GoodsReceivedNoteNo>=#i_GrnStartNo AND GRN.GoodsReceivedNoteNo<=#i_GrnEndNo or GRN.CreatedOn>=#d_StartDate AND GRN.CreatedOn<=#d_EndDate
WHERE CAST( GRND.CreatedOn AS DATE)>=#d_StartDate AND GRN.LocationID=1 AND CAST( GRND.CreatedOn AS DATE) <=#d_EndDate AND GRN.GoodsReceivedNoteNo>= #i_GrnStartNo AND GRN.GoodsReceivedNoteNo <=#i_GrnEndNo
To find the problem in the big queries follow this instructions
Copy and Paste the body of stored proc to a new query window
change the columns in select to *. I mean change your query to select * from
declare the parameters at the top of query and set the values to them
Start commenting the joins and run the query to see which one makes it to return no rows. you might need to comment the corresponding conditions in where statement.
I hope this helps you
Mention The Size of varchar
#i_GrnStartNo varchar(50),
#i_GrnEndNo varchar(50),

sql server update from select

Following the answer from this post, I have something like this:
update MyTable
set column1 = otherTable.SomeColumn,
column2 = otherTable.SomeOtherColumn
from MyTable
inner join
(select *some complex query here*) as otherTable
on MyTable.key_field = otherTable.key_field;
However, I keep getting this error:
The column prefix 'otherTable' does
not match with a table name or alias
name used in the query.
I'm not sure what's wrong. Can't I do such an update from a select query like this?
Any help would be greatly appreciated.
(I'm using *blush* sql server 2000.)
EDIT:
here's the actual query
update pdx_projects set pr_rpc_slr_amount_year_to_date = summary.SumSLR, pr_rpc_hours_year_to_date = summary.SumHours
from pdx_projects pr join (
select pr.pr_pk pr_pk, sum(tc.stc_slr_amount) SumSLR, sum(tc.stc_worked_hours) SumHours from pdx_time_and_cost_from_rpc tc
join pdx_rpc_projects sp on tc.stc_rpc_project_id = sp.sol_rpc_number
join pdx_rpc_links sl on sl.sol_fk = sp.sol_pk
join pdx_projects pr on pr_pk = sl.pr_fk
where tc.stc_time_card_year = year(getdate())
group by pr_pk
) as summary
on pr.pr_pk = summary.pr_pk
and the actual error message is
Server: Msg 107, Level 16, State 2,
Line 1 The column prefix 'summary'
does not match with a table name or
alias name used in the query.
I submit to you this altered query:
update x
set x.pr_rpc_slr_amount_year_to_date = summary.sumSLR,
x.pr_rpc_hours_year_to_date = summary.sumHours
from pdx_projects x
join (
select pr.pr_pk as pr_pk,
sum(tc.stc_slr_amount) as SumSLR,
sum(tc.stc_worked_hours) as SumHours
from pdx_time_and_cost_from_rpc tc
join pdx_rpc_projects sp on tc.stc_rpc_project_id = sp.sol_rpc_number
join pdx_rpc_links sl on sp.sol_pk = sl.sol_fk
join pdx_projects pr on sl.pr_fk = pr.pr_pk
where tc.stc_time_card_year = year(getdate())
group by pr.pr_pk
) as summary
on x.pr_pk = summary.pr_pk
Notably different here: I don't re-use the alias pr inside and outside of the complex query. I re-ordered the joins the way I like them (previously referenced table first,) and explicitly notated pr_pk in 2 places. I also changed the update syntax to use update <alias>.
Maybe not the answer you're looking for, but instead of generating hugely complex queries, I usually default to inserting the some complex query here into a table variable. Then you can do a simple update to MyTable with a join to the table variable. It may not be quite as efficient, but its much easier to maintain.
I couldn't replicate your error using SQL 2008 in 80 compatibility level. While this option doesn't guarantee that I'll get the same results as you, nothing appears to be out of place.
create table pdx_projects
(
pr_rpc_slr_amount_year_to_date varchar(max)
, pr_rpc_hours_year_to_date varchar(max)
, pr_pk varchar(max)
)
create table pdx_time_and_cost_from_rpc
(
stc_slr_amount decimal
, stc_worked_hours decimal
, stc_rpc_project_id varchar(max)
, stc_time_card_year varchar(max)
)
create table pdx_rpc_projects
(
sol_rpc_number varchar(max)
, sol_pk varchar(max)
)
create table pdx_rpc_links
(
sol_fk varchar(max)
, pr_fk varchar(max)
)
update pdx_projects
set
pr_rpc_slr_amount_year_to_date = summary.SumSLR
, pr_rpc_hours_year_to_date = summary.SumHours
from
pdx_projects pr
join (
select pr.pr_pk pr_pk
, sum(tc.stc_slr_amount) SumSLR
, sum(tc.stc_worked_hours) SumHours
from pdx_time_and_cost_from_rpc tc
join pdx_rpc_projects sp on tc.stc_rpc_project_id = sp.sol_rpc_number
join pdx_rpc_links sl on sl.sol_fk = sp.sol_pk
join pdx_projects pr on pr_pk = sl.pr_fk
where tc.stc_time_card_year = year(getdate())
group by pr_pk
) as summary
on pr.pr_pk = summary.pr_pk

T-SQL Nested Subquery

Not being a SQL expert, and also only being semi-competent in CTE, how can I code this statement use the resultset from the following subquery within the main query, as our SQL Server is 2000.
declare #subcategoryConcatenate varchar(3999)
set #subcategoryConcatenate = ''
select #subcategoryConcatenate = #subcategoryConcatenate + pumpCategoryName + ',' FROM
(SELECT
SCD.PUMPCATEGORYNAME,
SCD.ENGINECATEGORYNAME,
SCD.DETAILEDDESCRIPTION
FROM PRTTICKHDR PHDR
INNER JOIN BIDHDR BHDR ON PHDR.DELIV_TICKET_NUMBER = BHDR.DTICKET
INNER JOIN PRTTICKITEM PITM ON PHDR.CONNECTION_ID = PITM.CONNECTION_ID AND PHDR.DELIV_TICKET_NUMBER = PITM.DELIV_TICKET_NUMBER
LEFT JOIN SUBCATEGORYDESCRIPTION SCD ON PITM.ITEM = SCD.PUMPCATEGORY
WHERE SCD.pumpCategoryName IS NOT NULL)
subcategoryDescription
select #subcategoryConcatenate
SELECT
PHDR.CONNECTION_ID AS CONNECTION_ID,
BHDR.OFFICE AS OFFICE,
CMP.NAME AS DEPOT,
CMP.ADDR1 AS DEPOT_ADDR1,
CMP.ADDR2 AS DEPOT_ADDR2,
CMP.CITY AS DEPOT_CITY,
CMP.STATE AS DEPOT_STATE,
CMP.ZIP AS DEPOT_ZIP,
CMP.PHONENUM AS DEPOT_PHONE,
CMP.FAXNUM AS DEPOT_FAX,
ACT.NAME AS ACTIVITY,
SAL.SALES_PERSON_NAME AS SALESPERSON,
BHDR.DTICKET AS DELIV_TICKET_NUMBER,
BHDR.PO_NUMBER,
BHDR.CREATED AS CREATED_DATE,
BHDR.DDATE AS ESTIMATED_START_DATE,
BHDR.PROJ_STOP_DATE AS PROJECTED_STOP_DATE,
CUR.ID,
CUR.CODE,
CUR.EXCHANGE_RATE,
CST.TERMS,
BHDR.ORDBY AS ORDERED_BY,
PHDR.ORDERED_BY_CONTACT,
BHDR.ACCT AS ACCOUNT,
BHDR.NAME AS CUSTOMER,
BHDR.ADDR1 AS CUST_ADDR1,
BHDR.ADDR2 AS CUST_ADDR2,
BHDR.CITY AS CUST_CITY,
BHDR.STATE AS CUST_STATE,
BHDR.ZIP AS CUST_ZIP,
PHDR.SHIP_TO_NAME,
PHDR.SHIP_TO_ADDR1,
PHDR.SHIP_TO_ADDR2,
PHDR.SHIP_TO_CITY,
PHDR.SHIP_TO_STATE,
PHDR.SHIP_TO_ZIP,
PITM.PRINT_SEQUENCE,
PITM.ITEM,
PITM.SUBGROUP,
PITM.DESCRIPTION,
SCD.PUMPCATEGORYNAME,
SCD.ENGINECATEGORYNAME,
SCD.DETAILEDDESCRIPTION,
PITM.QUANTITY,
PITM.UNIT_OF_MEASURE,
PITM.BILLING_LOGIC_TYPE,
PITM.INVENTORY_TYPE,
PITM.CHARGEABLE_DAYS,
PITM.MINIMUM_CHARGE,
PITM.WEEKLY_CHARGE,
PITM.MONTHLY_CHARGE,
PITM.UNINVOICED_NET,
PITM.UNINVOICED_VAT
FROM PRTTICKHDR PHDR
INNER JOIN BIDHDR BHDR ON PHDR.DELIV_TICKET_NUMBER = BHDR.DTICKET
INNER JOIN PRTTICKITEM PITM ON PHDR.CONNECTION_ID = PITM.CONNECTION_ID AND PHDR.DELIV_TICKET_NUMBER = PITM.DELIV_TICKET_NUMBER
INNER JOIN COMPANY CMP ON BHDR.OFFICE = CMP.OFFICE
LEFT JOIN SUBCATEGORYDESCRIPTION SCD ON PITM.ITEM = SCD.PUMPCATEGORY
INNER JOIN ACTIVITIES ACT ON BHDR.ACTIVITY_ID = ACT.ID
INNER JOIN SALES_PERSON SAL ON BHDR.SALES_PERSON = SAL.SALES_PERSON
INNER JOIN CUSTOMERS CST ON BHDR.ACCT = CST.CUSTNUM
INNER JOIN CURRENCY CUR ON CST.CURRENCY_ID = CUR.ID
ORDER BY
BHDR.DTICKET,
PITM.PRINT_SEQUENCE
ASC
SQL Server 2000 doesn't support CTEs. Your options are to either make a view out of the subquery if it's used a lot, or to do an inline view:
select
.. stuff..
from
table1 t1
join table2 t2 on ...stuff...
join (
select
...
from
...
where
...
) inline on ... stuff ...
where
....
You need a user-defined function.
From the looks of it, each PRTTICKITEM can have more than one PUMPCATEGORY?
(The question needs to better explain the desired results.)
In that case, your UDF would look something like this:
CREATE FUNCTION GetPumpCategoriesByItem (#ItemID int)
RETURNS varchar (8000)
AS
BEGIN
DECLARE
#CategoryList varchar (8000)
SET #CategoryList = NULL -- MUST be null to avoid leading comma.
SELECT
#CategoryList = COALESCE (#CategoryList + ', ', '') + SCD.PUMPCATEGORYNAME
FROM
SUBCATEGORYDESCRIPTION SCD
WHERE
SCD.PUMPCATEGORY = #ItemID
ORDER BY
SCD.PUMPCATEGORYNAME
RETURN #CategoryList
END
.
To use it would be something like this:
SELECT
PITM.ITEM,
dbo.GetPumpCategoriesByItem (PITM.ITEM),
... ...
FROM
... ...
INNER JOIN PRTTICKITEM PITM ON ... ...
... ...