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

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.

Related

Select Stored Procedure priting a sum column on every row. Should only be on one

I have a query that lists all the parts for a specified job with their price. I have a total sum column that I only want to print once but it calculates the total every row. I can't figure out a solution? I've added an image of an example result set. I want the 318 to appear in the last row only. Is this possible?
use SBS
IF  EXISTS (SELECT * FROM sys.objects 
WHERE object_id = OBJECT_ID(N'partPrices')
AND type in (N'P', N'PC'))
DROP PROCEDURE partPrices
GO
CREATE PROCEDURE partPrices
(#job_name VARCHAR(30),
#job_type_id INT)
AS
BEGIN
SELECT
job.job_name, job_type.job_type_desc,
distributor.distributor_name,
part.part_name, part.price,
Total_part_price = (SELECT SUM(part.price) FROM part)
FROM
job
INNER JOIN
job_type ON job.job_type_id = job_type.job_type_id
INNER JOIN
part ON job.job_id = part.job_id
INNER JOIN
distributor ON part.distributor_id = distributor.distributor_id
WHERE
job.job_name LIKE '%' + #job_name + '%'
AND job_type.job_type_id = #job_type_id
GROUP BY
job.job_name, job_type.job_type_desc, part.part_name,
part.price, distributor.distributor_name
END
enter image description here
SELECT job.job_name,
job_type.job_type_desc,
distributor.distributor_name,
part.part_name,
part.price,
CASE
WHEN LAG(part_name) OVER(PARTITION BY part.part_name ORDER BY part_name) IS NULL
THEN NULL
ELSE SUM(part.price) OVER(PARTITION BY part.part_name)
END total
FROM job
INNER JOIN job_type ON job.job_type_id = job_type.job_type_id
INNER JOIN part ON job.job_id = part.job_id
INNER JOIN distributor ON part.distributor_id = distributor.distributor_id
WHERE job.job_name LIKE '%'+#job_name+'%'
AND job_type.job_type_id = #job_type_id
GROUP BY job.job_name,
job_type.job_type_desc,
part.part_name,
part.price,
distributor.distributor_name;

TSQL Conditional Join Statement?

I am working on a dynamic query that allows me to define field types in a database table and then pull a list of user defined fields that were selected during the creation of a dashboard along with the values that were chosen for each of the logic operators.
For example, use can choose field1 which is employeeID. They can then provide the ID they want to search by and it will store the fieldID and fieldValue in a table for when we need to render the data.
Now depending on the field that was chosen, I may need to join up another table to get further information such as the employees name.
While this is simple enough, the tricky part comes into play when having to join the value against multiple possible tables. If I stored an employeeID, I would join that field with the employee table. However, if I stored a storeID, I would need to join that field with the stores table instead.
Here was my thinking before I got to the end and realized I was stuck. Basically, I was going to say "if this field was a people table isPeople=1 then join our employeeTable.
If this field isTool=1, join our tools table.
I essentially have a fieldType and a fieldValue and based on the type, I need to join a specific table on the value I have stored.
As I was working through this making it dynamic sql, I realized that I couldn't use the fl.* fields to create my IF conditions.
ie. IF (fl.isPeople =1) BEGIN ... JOIN Employee Table ... END
I thought taking the dynamic approach would have been the only way to do this but now I can't think of a solution to my problem.
In Conclusion...
I am trying to join tables and query fields based on a condition. Since I couldn't seem to do that in my normal stored procedure, I tried to do it dynamically and ended up here and this very confusion problem I am trying to explain.
Let me know if I can further clarify.
Update:
USE [red]
GO
/****** Object: StoredProcedure [dbo].[ti2_fetch_dashboard] Script Date: 9/15/2016 9:55:39 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Carl
-- Create date: Sept 13, 2016
-- Description: Fetch Single Dashboard for Editing
-- =============================================
ALTER PROCEDURE [dbo].[ti2_fetch_dashboard_test]
#dashboardID INT, #SQL NVARCHAR(MAX) = ''
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Fetch our dashboard
SELECT #SQL = 'SELECT d.dashboardID,
d.dashboardOwner,
e.PreferredName AS ownerFirst,
e.LastName AS ownerLast,
e.NTID AS ownerNTID,
d.dashboardTitle,
d.dashboardDescription,
d.dashboardType,
d.creator,
d.timestamp,
d.lastUpdate,
d.isDeleted,
(SELECT sub.QID AS subscriberQID,
e.PreferredName AS subscriberFirst,
e.LastName AS subscriberLast,
e.NTID AS subscriberNTID
FROM dbo.ti_dashboard_subscribers AS sub
LEFT OUTER JOIN
dbo.EmployeeTable AS e
ON sub.QID = e.QID
WHERE sub.dashboardID = d.dashboardID
FOR XML PATH (''options''), ELEMENTS, TYPE, ROOT (''subscribers'')),
(SELECT f.fid,
f.fieldID,
f.[order],
cfg.primaryAllowed,
cfg.secondaryAllowed,
cfg.exportAllowed,
mf.fieldName,
mf.placeholder
FROM dbo.ti_dashboards_fields AS f
INNER JOIN
dbo.ti_dashboard_field_types AS ft
ON f.typeID = ft.fieldTypeID
INNER JOIN
dbo.ti_dashboard_master_fields_config AS cfg
ON f.fieldID = cfg.fieldID
INNER JOIN
dbo.ti_dashboards_master_fields AS mf
ON mf.fieldID = f.fieldID
WHERE f.dashboardID = d.dashboardID
AND ft.fieldTypeName = ''Primary''
ORDER BY f.[order] ASC
FOR XML PATH (''fields''), ELEMENTS, TYPE, ROOT (''primaryFields'')),
(SELECT f.fid,
f.fieldID,
f.[order],
cfg.primaryAllowed,
cfg.secondaryAllowed,
cfg.exportAllowed,
mf.fieldName,
mf.placeholder
FROM dbo.ti_dashboards_fields AS f
INNER JOIN
dbo.ti_dashboard_field_types AS ft
ON f.typeID = ft.fieldTypeID
INNER JOIN
dbo.ti_dashboard_master_fields_config AS cfg
ON f.fieldID = cfg.fieldID
INNER JOIN
dbo.ti_dashboards_master_fields AS mf
ON mf.fieldID = f.fieldID
WHERE f.dashboardID = d.dashboardID
AND ft.fieldTypeName = ''Secondary''
ORDER BY f.[order] ASC
FOR XML PATH (''fields''), ELEMENTS, TYPE, ROOT (''secondaryFields'')),
(SELECT f.fid,
f.fieldID,
f.[order],
cfg.primaryAllowed,
cfg.secondaryAllowed,
cfg.exportAllowed,
mf.fieldName,
mf.placeholder
FROM dbo.ti_dashboards_fields AS f
INNER JOIN
dbo.ti_dashboard_field_types AS ft
ON f.typeID = ft.fieldTypeID
INNER JOIN
dbo.ti_dashboard_master_fields_config AS cfg
ON f.fieldID = cfg.fieldID
INNER JOIN
dbo.ti_dashboards_master_fields AS mf
ON mf.fieldID = f.fieldID
WHERE f.dashboardID = d.dashboardID
AND ft.fieldTypeName = ''Export''
ORDER BY f.[order] ASC
FOR XML PATH (''fields''), ELEMENTS, TYPE, ROOT (''exportFields'')),
(SELECT l.[fieldID],
-- Get the details of each of those fields
(SELECT fl.queryField,
fl.allowMultiple,
fl.isPeople,
fl.isDate,
fl.isSelect,
fl.isInput,
fl.isTool,
fl.selectOptions,
-- Get the values associcated with the fields
(SELECT dv.value';
-- If fl.isPeople = 1
SELECT #SQL += ', e.PreferredName AS FirstName, e.LastName, e.NTID, e.QID ';
-- If fl.isTool = 1
SELECT #SQL += ', t.toolName, t.toolType ';
-- Primary Table
SELECT #SQL += 'FROM dbo.ti_dashboards_logic AS dv ';
-- If fl.isPeople = 1
SELECT #SQL += 'LEFT OUTER JOIN dbo.EmployeeTable AS e ON dv.value = e.QID ';
-- If fl.isTool = 1
SELECT #SQL += 'LEFT OUTER JOIN ti_tools AS t ON dv.value = t.tool ';
-- Rest of Statement
SELECT #SQL += 'WHERE dv.fieldID = l.fieldID
AND dv.dashboardID = d.dashboardID
FOR XML PATH (''data''), TYPE, ELEMENTS, ROOT (''values''))
FROM dbo.ti_dashboard_master_fields_config AS fl
WHERE fl.fieldID = l.fieldID
AND l.dashboardID = d.dashboardID
FOR XML PATH (''fields''), TYPE, ELEMENTS, ROOT (''logicMeta''))
FROM [red].[dbo].[ti_dashboards_logic] AS l
WHERE l.dashboardID = d.dashboardID
GROUP BY l.fieldID, l.dashboardID
FOR XML PATH (''fields''), TYPE, ELEMENTS, ROOT (''logicFields'')),
(SELECT sdb.dashboardID ,
sdb.fieldID ,
sdb.sort ,
sdb.[order] ,
mf.fieldName
FROM dbo.ti_dashboards_sorting AS sdb
JOIN dbo.ti_dashboard_master_fields_config AS sf
ON sdb.fieldID = sf.fieldID
JOIN dbo.ti_dashboards_master_fields AS mf
ON sf.fieldID = mf.fieldID
WHERE sdb.dashboardID = d.dashboardID
ORDER BY sdb.[order] ASC
FOR XML PATH (''fields''), TYPE, ELEMENTS, ROOT (''sortingFields'')
)
FROM dbo.ti_dashboards AS d
LEFT OUTER JOIN
dbo.EmployeeTable AS e
ON d.dashboardOwner = e.QID
WHERE d.dashboardID = #_dashboardID
AND d.isDeleted = 0
FOR XML PATH (''data''), ELEMENTS, TYPE, ROOT (''root'')';
EXEC sp_executesql #SQL, N'#_dashboardID INT', #_dashboardID = #dashboardID
END
You cannot join tables dynamically, driven by data and different number of columns for each row.
You just need to use UNION to combine the results from multiple SELECT queries. Each SELECT query will have different joins and WHERE statements (isPeople, isTool, etc).
Or you can join all relevant tables and add more conditions in ON statement like below pseudo-code:
SELECT e.xxxx, t.yyyy, dv.zzzz, fl.ffff
FROM dbo.ti_dashboards_logic AS dv
JOIN dbo.ti_dashboard_master_fields_config AS fl ON ....
LEFT OUTER JOIN dbo.EmployeeTable AS e ON dv.value = e.QID AND fl.isPeople = 1
LEFT OUTER JOIN ti_tools AS t ON dv.value = t.tool AND fl.isTool = 1
So each row has same number of columns, and t.yyyy and e.xxxx will be NULL or not NULL depending on fl.isTool and fl.isPeople values.

Grouping and Pipe delimiter (Newbee) SQL Server 2008 R2

I created this script:
SELECT Distinct
rtrim(Insurances.EligibilityPayorNumber) as InsurancePayorCode
, rtrim(ContractFacilityProviders.NPI) as ProviderID
, rtrim(PatientInsuranceProfiles.Insurance1PolicyNumber) as SubscriberInsuranceID
, rtrim(PatientInsuranceProfiles.Insurance1PolicyGroupNumber) as SubscriberGroupNumber
, rtrim(PatientDemographics.firstname) as SubscriberFirstName
, rtrim(PatientDemographics.MiddleInitial) as SubscriberMiddleInitial
, rtrim(PatientDemographics.Lastname) as SubscriberLastName
, rtrim(PatientDemographics.sex) as Gender
, rtrim(PatientDemographics.DateofBirth) as DOB
, ScheduleEntry.ScheduleDate as DateofService
, PatientDemographics.AccountNumber as TrackingID
FROM ScheduleEntry
LEFT JOIN PatientDemographics
ON ScheduleEntry.PatientAccount = PatientDemographics.AccountNumber
LEFT JOIN Reasons
ON ScheduleEntry.ReasonCode = Reasons.ReasonCode
LEFT JOIN Providers
ON ScheduleEntry.ResourceCode = Providers.MedStarProviderIdentifier
LEFT JOIN Facilities
ON ScheduleEntry.FacilityCode = Facilities.MedStarFacilityIdentifier
LEFT JOIN [john-pc\sqlexpress].[Global].[dbo].[PatientStatuses] TAB2
on ScheduleEntry.PatientStatus = TAB2.PatientStatusCode
LEFT JOIN AddedResource
ON ScheduleEntry.ResourceCode = AddedResource.AddedResourceCode
LEFT JOIN Caregiver
ON ScheduleEntry.ResourceCode = Caregiver.CaregiverCode
LEFT JOIN ReasonScripts
ON ScheduleEntry.ReasonCode = ReasonScripts.Reasoncode
LEFT JOIN Scripts
on Reasonscripts.Scriptcode = Scripts.ScriptCode
LEFT JOIN PatientInsuranceProfiles
ON ScheduleEntry.PatientAccount = PatientInsuranceProfiles.PatientAccountNumber
LEFT JOIN Insurances
ON PatientInsuranceProfiles.Insurance1Mnemonic = Insurances.Mnemonic
LEFT JOIN ContractFacilityProviders
ON PatientDemographics.PrimaryPhysician = ContractFacilityProviders.ProviderIdentifier
WHERE ScheduleEntry.ScheduleDate >= getdate()
and ScheduleEntry.ScheduleDate <= getDate() +1
and PatientinsuranceProfiles.ActiveFlag = 1
and EligibilityPayorNumber > = 1
ORDER By SCHEDULEDATE
I would like to do a few things and can't figure out how:
The DOB of is returning a value of Nov 6 1939 12:00AM and I need it to be mmddyyyy.
I need to group by TrackingID which can be the same on multiple lines. The data would always be the same.
What can I add to the script so when I run it as a SQL it will save as pipe delimited?
For your DOB, this can be used in your SELECT. Note, it will be of type VARCHAR and no longer a datetime.
SELECT REPLACE(CONVERT(VARCHAR(10),PatientDemographics.DateofBirth,101),'/','') AS DOB
I notice your RTRIM and they could be necessary for your output, but this is just some free knowledge on SQL server and trailing spaces for comparisions:
https://support.microsoft.com/en-us/kb/316626
DECLARE #s1 varchar(10)
DECLARE #s2 varchar(10)
set #s1 = 'nospace'
set #s2 = '3spaces '
select len(#s1), len(#s2)

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"

From Procedure to View

Code below works perfect as procedure.
How can I transform or change the same code below so that it can work in View or as View code or View?
Can I drop View?
ALTER proc [dbo].[NewOne_1]
as
begin
set nocount on
if object_ID('TEMPDB..#TableA') <> ''
drop table # TableA
select
*
into # TableA
from vd_View po
if object_ID('TEMPDB..#FirstSDate') is not null
drop table #FirstSDate
select
Pt_id = Pat_Id,
Date_of_First_Shipment = min(DeliveryDate)
into #FSDate
from # TableA po
group by Pat_Id
if object_ID('TEMPDB..#LastSDate') is not null
drop table #LastShipDate
select
Pt_id = Pat_Id,
Date_of_Last_Shipment = max(DeliveryDate)
into #LastShipDate
from # TableA po
group by Pat_Id
SELECT PtData.Pat_No Progress_Pat_ID
,C_S = case when dbo.fn_GetBusinessDays(firstship.Date_of_First_Shipment,LastShip.Date_of_Last_Shipment) > 80 then 'Yes'
when dbo.fn_GetBusinessDays(firstship.Date_of_First_Shipment,LastShip.Date_of_Last_Shipment) <= 80 then 'No'
else ''
end
,P_Last_Name = PtData.P_LName
,PtData.DReg Reg
FROM dbo.tbld_PatSum PtData
inner join vd_PSum ps
on PtData.P = ps.P_ID
inner join S_M.dbo.Pat__c ps1
on PtData.Pt_ID = ps1.Id
left join #FirstShipDate firstship
on PtData.Pt_ID = firstship.Pt_Id
left join #LastShipDate LastShip
on PtData.Pt_ID = LastShip.Pt_Id
WHERE PtData.Pat_No IS NOT NULL
AND PtData.ActiveStatus<>'Gen Info'
set nocount off
end
I'm guessing that you're wanting to be able to use this to join with something else. You cannot put this into a view. However you may be able to put this in a table-valued function which would allow you to accomplish what I think you're after.
--just took your code (it's quite messy), the dbo.fn_GetBusinessDays function must be deterministic in order to work in a view
create view test as
SELECT
PtData.Pat_No Progress_Pat_ID
,C_S = case when dbo.fn_GetBusinessDays(firstship.Date_of_First_Shipment,LastShip.Date_of_Last_Shipment) > 80 then 'Yes'
when dbo.fn_GetBusinessDays(firstship.Date_of_First_Shipment,LastShip.Date_of_Last_Shipment) <= 80 then 'No'
else ''
end
,P_Last_Name = PtData.P_LName
,PtData.DReg Reg
FROM dbo.tbld_PatSum PtData
inner join vd_PSum ps
on PtData.P = ps.P_ID
inner join S_M.dbo.Pat__c ps1
on PtData.Pt_ID = ps1.Id
left join (
select
Pt_id = Pat_Id,
Date_of_First_Shipment = min(DeliveryDate)
from vd_View po
group by Pat_Id ) firstship
on PtData.Pt_ID = firstship.Pt_Id
left join (select
Pt_id = Pat_Id,
Date_of_Last_Shipment = max(DeliveryDate)
from vd_View po
group by Pat_Id ) LastShip
on PtData.Pt_ID = LastShip.Pt_Id
WHERE PtData.Pat_No IS NOT NULL
AND PtData.ActiveStatus<>'Gen Info'