SQL Code working in SSMS but not in Report Builder 3.0 - sql

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"

Related

Returning values from different rows in a stored procedure as different values

I have a stored procedure:
`SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [ebs].[DB_Task_ONEYCRPRaport]
--#startDate DATE,
--#endDate DATE
AS
BEGIN
SELECT DISTINCT
CAST(A.ExternalMerchantId as varchar) "Merchant_guid", -- ok
CAST(C.CreatedOn AS DATE) "Purchase_date", --ok
CAST(C.CreatedOn AS TIME) "Purchase_hour", --ok
C.ContractNo "Funding_reference",--ok
APP.OrderNo "External_reference", --ok
A.CustomerInternalId "Customer_external_code",--ok
CASE WHEN I.TotalAmountToPay = 0 THEN '-' ELSE '+' END "Total_amount_symbol",--ok
CASE WHEN I.TotalAmountToPay = 0 THEN I.TotalAmountToRecover ELSE I.TotalAmountToPay END "Total_amount"
from ebs.Account as A
JOIN ebs.FTOS_CB_Contract AS C ON A.Accountid = C.CustomerId
JOIN ebs.FTOS_CB_BankAccount AS BA ON BA.FTOS_CB_BankAccountid = C.MainBankAccountId
JOIN ebs.FTOS_CB_BankAccountOperation AS BAO ON BAO.BankAccountId = BA.FTOS_CB_BankAccountid
JOIN Ebs.FTOS_CMB_Currency AS CU ON CU.FTOS_CMB_Currencyid = C.CurrencyId
JOIN ebs.FTOS_TPM_Invoice AS I ON I.BankAccountId = BA.FTOS_CB_BankAccountid
JOIN ebs.FTOS_TPM_InvoiceDetail AS ID ON ID.InvoiceId = I.FTOS_TPM_Invoiceid
JOIN ebs.FTOS_BNKAP_Application AS APP ON APP.ContractId = ID.ContractId
JOIN ebs.FTOS_CB_Payment AS P ON I.FTOS_TPM_Invoiceid=P.InvoiceId
JOIN ebs.FTOS_BP_BankingProduct AS BP ON BP.FTOS_BP_BankingProductid=(SELECT CO.ProductId from ebs.FTOS_CB_Contract AS CO where CO.FTOS_CB_Contractid = ID.ContractId)
JOIN ebs.FTOS_TPM_PreInvoiceDetail AS PID ON PID.ContractId = C.FTOS_CB_Contractid
left JOIN ebs.FTOS_ONEY_ICE_Repayment as R ON P.PaymentNo = R.PaymentNo
left JOIN ebs.FTOS_ONEY_ICE_Repayment_Details AS RD ON RD.FTOS_ONEY_ICE_Repaymentid = R.FTOS_ONEY_ICE_Repaymentid -- detalii plati efectuate
left JOIN ebs.FTOS_ONEY_ICE_Libra_ReceivedPayments AS RP ON RP.FTOS_CB_Contractid = C.FTOS_CB_Contractid --and DATEPART(week, C.CreatedOn) = DATEPART(week, GETDATE()) take current week results
END`
I have another table where commissions are stored, the problem is I don't know how to select them in my stored procedure if they are on separate columns:
Here is the test query:
SELECT PID.*
FROM [ebs].[FTOS_TPM_PreInvoiceDetail] as PID
WHERE PID.Name = 'name'
Basically for this example I want those values 20 and 5 to be selected in my stored procedures as two different values, how can I achieve that?
I tried created another stored procedure, but I think is a very bad idea.

Order By Statement

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

Updating table with procedure on column where last date is

I can't figure out how to create a procedure that only updates table automatically.
What I am trying to do is update table into db.New_table from yesterday date on SENDDATE aka. table has all the information from 01.01.1998 till 09.01.2016, but need to create automated procedure to update that table automatically
SELECT
account.STRING0,
activity.CONTACT,
account.STRING2,
activity.TEMPLATE,
activity.NAME ,
val1.type_code,
val2.type_name,
activity.EXECUTION,
activity.SENDDATE,
Activity.OPENDATE,
Activity.CLICKDATE
into db.New_table
FROM
db.1_account account
Join
db.2_activity activity
ON
(account.object = activity.contact)
left JOIN
db.VAL val1
ON val1.obj_row_id = activity.CAMPAIGN AND (val1.FIELD in(850))
left JOIN
db.VAL val2
ON val2.obj_row_id = activity.CAMPAIGN AND (val2.FIELD in(851))
Commit
End
Guy who left the company sent me example, but he did not have the time to explain to me how to use that query.
ALTER PROCEDURE "DWTMP"."LOAD_CHANGED_VALUES"()
AS
BEGIN
insert into DW_TMP.DW_TRANSFER_LOG (TRANSFER_CODE, TABLE_NAME, LOG_DATE_TIME, LOG_DATE, OPERATION, LOG_TEXT)
SELECT 'LOAD_CHANGED_VALUES', 'TMP_CHANGED_RES', GETDATE(), DATE(GETDATE()), 'START', 'Transfer started'
COMMIT
DECLARE #TRANSFER_STAMP TIMESTAMP
SET #TRANSFER_STAMP = GETDATE()
DECLARE #TRANSFER_STAMP1 TIMESTAMP
SET #TRANSFER_STAMP1 = GETDATE()
TRUNCATE TABLE DW_TMP.tmp_changed_res
insert into dw_tmp.tmp_changed_res(res_id, modified_date_time, modifier_CODE)
select rh.res_id, rh.trans_timestamp as modified_date_time , rh.performer as modifier_CODE
from SE.RES_HISTORY RH
join (SELECT RES_ID, MAX(TRANS_ID) TRANS_ID
from SE.RES_HISTORY RH
JOIN DW_TMP.PAR_LASTTRANSFER LT
ON LT.TABLE_CODE = 'RESERVATION'
WHERE RH.TRANS_TIMESTAMP BETWEEN DATEADD(HOUR,-1,LT.FROM_TRANSFER_DATE) AND TO_TRANSFER_DATE
AND RH.TRANS_TIMESTAMP < DATEADD(MINUTE,-5,#TRANSFER_STAMP)
GROUP BY RES_ID) t
on rh.res_id = t.res_id
and rh.trans_id = t.trans_id
NB!SQL Server (Sybase)
Visual data flow

Using results of JOIN statement to join on the results of another JOIN statement

I have the following 2 Join Statements:
--Get Total Hrs
DECLARE #BeginDate datetime, #EndDate datetime
set #BeginDate = '01-01-2013'
set #EndDate = '12-31-2013'
BEGIN
SELECT F.Type, E.Product, SUM(F.Hours * E.Amount) AS 'Total Hours'
FROM Hours H
INNER JOIN Equipment E
ON F.SN = E.SN
WHERE (F.Date BETWEEN #BeginDate AND #EndDate)
GROUP BY F.Type, E.Product
ORDER BY Product ASC
END
--Get Number of Unscheduled Removals
DECLARE #BeginDate1 datetime, #EndDate1 datetime
set #BeginDate1 = '01-01-2013'
set #EndDate1 = '12-31-2013'
BEGIN
SELECT LEFT(dbo.fn_GetPartName(R.PartID),CHARINDEX('-',dbo.fn_GetPartName(R.PartID), 1) - 1) AS 'Part No',
Count(s.status) AS NumberUnscheduledRemovals
FROM Repair R
INNER JOIN Conversion C
ON R.Performed = C.Performed
AND R.Confirmed = C.Confirmed
INNER JOIN Status S
ON C.StatusID = S.StatusID
WHERE (R.Received BETWEEN #BeginDate1 AND #EndDate1)
AND (S.Status = 'UNSCHEDULED')
GROUP BY LEFT(dbo.fn_GetPartName(R.PartID),CHARINDEX('-',dbo.fn_GetPartName(R.PartID), 1) - 1)
ORDER BY LEFT(dbo.fn_GetPartName(R.PartID),CHARINDEX('-',dbo.fn_GetPartName(R.PartID), 1) - 1) ASC
END
Both queries have results including part numbers (these have the same values). I want to INNER JOIN the results from both queries on the resulting part numbers. have been trying for a while but cant seem to get the syntax right to do it.
Use a temp table using CREATE TABLE #TempPartNum1 & #TempPartNum2.
Grab all the relevant data from the first two queries and put them in the temp tables, then join the temp tables.
You could also use a CTE ("Common Table Expression"):
;WITH QueryOne AS (
... put your first query here
), QueryTwo AS (
... put your second query here
) SELECT blah blah blah
FROM QueryOne INNER JOIN QueryTwo ON foo = bar
CTEs are very handy for things like this.

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